Your regular expression ^(?:([0]{0}?\d):)?([0-5]{1}?\d)$ - has 0{0}? , which makes the engine correspond to 0 exactly zero time (this token is ignored). It also has redundant {1} (since [0-5] will match a value from 0 to 5 exactly once). Please note that there is no reason to put one character in a character class (for example, [0] ), this can cause problems later when you need to configure the template. And more importantly, your regular expression contains an optional group (?:([0]{0}?\d):)? which can match one or zero times. So your regex allows you to type as 56 .
You can use the following regular expression:
/^\d:[0-5]\d$/
Watch the 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 line\d - one digit: - colon[0-5] - one digit from 0 to 5 range\d - one digit$ - end of line
source share