I want to validate a 5 digit number which should not be 00000. All numbers except 00000 are allowed.
examples : 01201 , 00001, 21436 , 45645 are valid numbers and 1, 12, 123, 1234, 00000 are invalid numbers.
I tried with ^([0-9]{5}[^(0){5}])$
but it was of no use.
Any help on this will be much appreciated.
Thanks.
I want to validate a 5 digit number which should not be 00000. All numbers except 00000 are allowed.
examples : 01201 , 00001, 21436 , 45645 are valid numbers and 1, 12, 123, 1234, 00000 are invalid numbers.
I tried with ^([0-9]{5}[^(0){5}])$
but it was of no use.
Any help on this will be much appreciated.
Thanks.
Share Improve this question edited Apr 7, 2014 at 12:09 mplungjan 178k28 gold badges180 silver badges240 bronze badges asked Apr 7, 2014 at 12:05 Naresh RavlaniNaresh Ravlani 1,62014 silver badges29 bronze badges 1- 4 what about string.length=5 && string != "00000"? [Edit: OK, testing for numberness requires regex, see @mplungjan's answer] – Jasper Commented Apr 7, 2014 at 12:09
4 Answers
Reset to default 9Using negative positive lookahead:
/^(?!0{5})\d{5}$/
/^(?!0{5})\d{5}$/.test('01201')
// => true
/^(?!0{5})\d{5}$/.test('00001')
// => true
/^(?!0{5})\d{5}$/.test('21436')
// => true
/^(?!0{5})\d{5}$/.test('1')
// => false
/^(?!0{5})\d{5}$/.test('12')
// => false
/^(?!0{5})\d{5}$/.test('00000')
// => false
No need for negative lookahead
Live Demo
function isvalid5(str) {
return str != "00000" && /^\d{5}$/.test(str);
}
You can use a negative look ahead:
^(?!0{5})\d{5}$
The negative loo ahead (?!...)
will fail the whole regex if what's inside it matches, \d
is a shortcut for [0-9]
.
for regex engines that do not support lookahead:
^(0000[1-9]|000[1-9][0-9]|00[1-9][0-9]{2}|0[1-9][0-9]{3}|[1-9][0-9]{4})$