Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript function to validate time 00:00 with regular expression

I am trying to create a javascript function with regular expression to validate and format the time 24 hours, accepting times without semicolon and removing spaces.
Examples:
If the user types "0100", " 100" or "100 " it would be accepted but formatted to "01:00"
If the user types "01:00" it would be accepted, with no need to format.

Thanks.

like image 564
Amra Avatar asked Jan 12 '10 11:01

Amra


People also ask

How does regular expression validate time in 24-hour format?

In a regular expression, we write this as ‹ 1[0-2]|0?[1-9] ›. 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] ›.

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 do you validate a regular expression?

You can use regular expressions to match and validate the text that users enter in cfinput and cftextinput tags. Ordinary characters are combined with special characters to define the match pattern. The validation succeeds only if the user input matches the pattern.

How do you evaluate a regular expression in JavaScript?

JavaScript | RegExp test() Method The RegExp test() Method in JavaScript is used to test for match in a string. If there is a match this method returns true else it returns false. Where str is the string to be searched. This is required field.


1 Answers

function formatTime(time) {
    var result = false, m;
    var re = /^\s*([01]?\d|2[0-3]):?([0-5]\d)\s*$/;
    if ((m = time.match(re))) {
        result = (m[1].length === 2 ? "" : "0") + m[1] + ":" + m[2];
    }
    return result;
}
alert(formatTime(" 1:00"));
alert(formatTime("1:00 "));
alert(formatTime("1:00"));
alert(formatTime("2100"));
alert(formatTime("90:00")); // false

Any call with invalid input format will return false.

like image 138
OcuS Avatar answered Oct 06 '22 20:10

OcuS