RegEx to match m: ss for input validation

I am trying to create RegEx to do the following:

  • only one number for minutes (0 to 9);
  • only two numbers for seconds (00 to 59);
  • must be in m: ss format.

So far I have this: ^(?:([0]{0}?\d):)?([0-5]{1}?\d)$

However, case 00, for example, seems to pass, and it should not, since it is not in the format m: ss.

+5
source share
3 answers

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
+10
source

If I am missing something, it 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 that gives a full explanation:

^ approve the position at the beginning of the line

[0-9] matches one character present in the list below 0-9, one character in the range 0 to 9

: matches the character: literally

[0-5] corresponds to one character present in the list below 0-5, one character in the range from 0 to 5

[0-9] matches one character present in the list below 0-9, one character in the range 0 to 9

$ statement position at end of line

+6
source

regular expression: /^\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); } }); 

A warning is issued only "2.12", the rest - invlaid,

+3
source

Source: https://habr.com/ru/post/1242612/


All Articles