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
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] ›.
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.
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.
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] ›.
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');
}
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With