I've been struggling to create a RegEx to fulfill the following:
So far I have this: ^(?:([0]{0}?\d):)?([0-5]{1}?\d)$
However the case 00 for example seems to be passing and it shouldn't, since it's not in the m:ss format.
Your regex - ^(?:([0]{0}?\d):)?([0-5]{1}?\d)$
- has a 0{0}?
that makes the engine match 0
exactly zero times (this token is ignored). It also has redundant {1}
(as [0-5]
will match a digit from 0
to 5
exactly one time). Note that there is no reason to place a single character into a character class (like [0]
), it might cause issues later when you need to adjust the pattern. And more importantly, your regex contains an optional group (?:([0]{0}?\d):)?
that can match one or zero times. Thus, your regex allows input like 56
.
You can use the following regex:
/^\d:[0-5]\d$/
See demo
var rx = /^\d:[0-5]\d$/;
var tests = ['0:00','1:34','156','3:67','45:55','56','4:344'];
for (var i = 0; i < tests.length; i++) {
document.getElementById('result').innerHTML += tests[i] + ": " + (rx.test(tests[i])) + "<br/>";
}
input:valid {
color: green;
}
input:invalid {
color: red;
}
<div id="result"/>
<input type="text" pattern="\d:[0-5]\d" /><br/>
Explanation:
^
- start of string\d
- one digit:
- a colon[0-5]
- one digit from 0
to 5
range\d
- one digit$
- end of stringUnless I am missing something this should be very simple...
^[0-9]:[0-5][0-9]$
var regex = /^[0-9]:[0-5][0-9]$/;
var input = $('input');
input.keyup(function() {
if (regex.test(input.val()))
input.removeClass('error');
else
input.addClass('error');
});
input.error {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input/>
Here is a working example, which provides a full explanation:
^ assert position at start of a line
[0-9] match a single character present in the list below 0-9 a single character in the range between 0 and 9
: matches the character : literally
[0-5] match a single character present in the list below 0-5 a single character in the range between 0 and 5
[0-9] match a single character present in the list below 0-9 a single character in the range between 0 and 9
$ assert position at end of a line
the regex is: /^\d:[0-5]\d$/
["2:12", // OK
// the rest are invalid:
"2:60","09:12", "13:2", "123:1", "123:23", "123:456"].forEach(function(s){
if (s.match(/^\d:[0-5]\d$/)) {
alert(s);
}
});
Only "2.12" will be alerted, the rest are invlaid,
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