Reputation: 9
I am trying to validate min 1 and max 59 with the following regexp but not working as expected.
^[1-5]?[1-9]$
What is wrong with the expression?
Upvotes: 0
Views: 99
Reputation:
Everyone busy trying to provide a solution missed the real question OP asked.
What is wrong with the expression?
Well here is your regex: ^[1-5]?[1-9]$
What you are trying to do is match a number having first digit (optional) in range 1 to 5
and second digit in range 1-9
. And since you want to match number from 1 to 59
, you will be missing is numbers like 10,20,30,40,50
as pointed out in one comment.
Upvotes: 1
Reputation: 630
It's work: ^([1-5][0-9]|[1-9])$
(@Tushar)
if (/^([1-5][0-9]|[1-9])$/.test(number)) {
// Successful match
} else {
// Match attempt failed
}
The better/faster way (without regex):
function validate(number) {
number = parseInt(number);
return number > 0 && number < 60;
}
for (var i = 0; i < 65; i++) {
console.log(validate(i));
}
Tested:
Upvotes: 2