Jafrul Sadek Nabil
Jafrul Sadek Nabil

Reputation: 85

JavaScript regex two string number separated by ( : ) individual max min calculation

I need to validate JavaScript string like "03:39" with Regex. Rules are following,

1.First part of the string which is before (:) is allowed from 0 to 24

2.Second part of the string which is after (:) is allowed from 0 to 59

3.Single digit number of both part can either be start with 0 like 01 or 02 or with out 0 like 1 , 2.

Now i have wrote a JavaScript regex code which is following.

var dateRegEx = /^n(0[0-2][0-4]|[0-24])(:)(0|[0-5][0-9]|[0-59])$/;
if ($(element).val().match(dateRegEx) === null) { 
// my rest of the code
}

now, when user insert 0:38, 01:38 or 02:59 it get validated but when the first part incensed after 2 like 03:38 it not validating the string. So what am i doing wrong ??

Upvotes: 1

Views: 75

Answers (2)

Code Maniac
Code Maniac

Reputation: 37755

Well i think you don't need regex here you can do directly like this

function check(input){
  let temp = input.split(':')
  return  (0 <= temp[0] && temp[0] <=24 ) && ( 0<= temp[1] && temp[1] <=59)
}

console.log(check('03:380'))
console.log(check('03:38'))
console.log(check('30:0'))

With regex you can do it like this

function check(input){
  return /^(?:[01]?[0-9]|[0-2][0-4]):[0-5]?[0-9]$/.test(input)
}


console.log(check('03:30'))
console.log(check('03:380'))
console.log(check('33:30'))
console.log(check('24:59'))
console.log(check('03:60'))
console.log(check('0:0'))
console.log(check('0:30'))

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370989

For hours, your current 0[0-2][0-4] requires three digits (none of which can be above 4), whereas [0-24] will only match one digit (a 0, 1, 2, or 4).

Rather, to match hours (00 to 24), you should use (?:2[0-4]|[01]?[0-9]); either a 2 followed by a number from 0 to 4, or an (optional) 0 or 1 followed by any other digit.

To match minutes (00 to 59), use [0-5]?[0-9] - an optional digit from 0 to 5, followed by a digit from 0 to 9.

^(?:2[0-4]|[01]?[0-9]):[0-5]?[0-9]$

https://regex101.com/r/0QxX7w/1

Note that if you're just matching a single character like :, don't put it in a character set. Also, because you don't want an n at the beginning of the match, remove it from the beginning of your pattern.

Upvotes: 1

Related Questions