Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for AM PM time format for jquery

I am being frustrated by a regular expression to mask the input field. I want to Limit input to hh:mm AM|PM format and I can't get this regex to work.

I use this regex in conjunction with a jquery tool from www.ThimbleOpenSource.com. It was the filter_input.js tool or whatever.

It seems to work for a simple regular expression but the one I came up with doesn't seem to work. This is my jsFiddle test link below.

jsFiddle

like image 611
SoftwareSavant Avatar asked Jan 11 '12 13:01

SoftwareSavant


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] ›.

What is jQuery regex?

It's used to match strings or parts of strings and for search and replace operations. jQuery uses regular expressions extensively for such diverse applications as parsing selector expressions, determining the type of browser in use, and trimming whitespace from text.

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.

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] ›.


2 Answers

I have made a jsfiddle example, based on the regular expression of the answer von Yuri: http://jsfiddle.net/Evaqk/

$('#test1, #test2').blur(function(){
    var validTime = $(this).val().match(/^(0?[1-9]|1[012])(:[0-5]\d) [APap][mM]$/);
    if (!validTime) {
        $(this).val('').focus().css('background', '#fdd');
    } else {
        $(this).css('background', 'transparent');
    }
});
like image 101
Armin Avatar answered Sep 18 '22 05:09

Armin


First of all, if you using it for input field, you should never let users input date or time information using text fields and hoping it will be in strict format.

But, if you insist:

/^(0?[1-9]|1[012])(:[0-5]\d) [APap][mM]$/

This regex will validate time in AM/PM format.

like image 38
YuS Avatar answered Sep 18 '22 05:09

YuS