Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate a HH:MM time

This is my javascript sample. How can it be improvised?

function a(id) 
{
    var n=document.getElementById(id);
    var re=/^[0-9]:[0-9] [to] [0-9]:[0-9]*$/;

    if(re.test(n.value))
    {
        n.style.backgroundColor="#52F40C";
    }
    else
    {
        window.alert("Invalid Entry");
        n.style.backgroundColor="#F40C0C";
        n.focus();
        n.value="";
    }
}

I wanna validate user input which should be for example 10:30 to 12:30. I'm a fresher please suggest me.

like image 580
suhas Avatar asked Jan 23 '13 04:01

suhas


People also ask

How does regular expression validate time in 12 hour format?

On a 12-hour clock, if the first digit is 0, the second digit allows all 10 digits, but if the first digit is 1, the second digit must be 0, 1, or 2. In a regular expression, we write this as ‹ 1[0-2]|0?[1-9] ›.

How does regular expression validate time in 24 hour format?

On a 24-hour clock, if the first digit is 0 or 1, the second digit allows all 10 digits, but if the first digit is 2, the second digit must be between 0 and 3. In regex syntax, this can be expressed as ‹ 2[0-3]|[01]?[0-9] ›. Again, the question mark allows the first 10 hours to be written with a single digit.

Which regex pattern can be used to find the time?

regex = "([01]?[0-9]|2[0-3]):[0-5][0-9]"; Where: ( represents the start of the group. [01]?[0-9] represents the time starts with 0-9, 1-9, 00-09, 10-19.


1 Answers

Use this regex for time format hh:mm

^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$

I have just placed the time format.Try to edit this for your requirement.

like image 189
Techy Avatar answered Nov 04 '22 12:11

Techy