I need to prevent entering 5
digit sequential numbers like 12345
, 45678
etc. in a text box.
I had tried with the following regular expression, but it is not working
var regex = /^\(?[0-9]{3}(\-|\)) ?[0-9]{3}-[0-9]{4}$/;
I need to prevent entering 5
digit sequential numbers like 12345
, 45678
etc. in a text box.
I had tried with the following regular expression, but it is not working
var regex = /^\(?[0-9]{3}(\-|\)) ?[0-9]{3}-[0-9]{4}$/;
Share
Improve this question
edited Oct 3, 2020 at 14:50
Penny Liu
17.4k5 gold badges86 silver badges108 bronze badges
asked Jun 14, 2016 at 11:33
Shijin TRShijin TR
7,76811 gold badges62 silver badges125 bronze badges
5
|
2 Answers
Reset to default 20It is better to use non regular expression based approach for this type of tasks. You can do this easily using indexOf
. Regular expressions for these patterns become really complicated and un-readable.
var pattern = '0123456789012345789' //to match circular sequence as well.
if (pattern.indexOf(input) == -1)
console.log('good input')
else
console.log('bad input')
Another approach is used Tilde (~)
operator in search functions. Using ~
on -1
converts it to 0
. The number 0 is a falsy value, meaning that it will evaluate to false when converted to a Boolean. Anything that is not falsy is truthy.
const input = '12345';
const pattern = '0123456789012345789';
if (~pattern.indexOf(input))
console.log('pattern in input');
else
console.log('pattern not in input');
or you can use the includes()
method:
const input = '12345';
const pattern = '0123456789012345789';
if (pattern.includes(input))
console.log('pattern in input');
else
console.log('pattern not in input');
(?!(?:01234|12345|23456|34567|45678|56789|67890|78901|89012|90123)$).*
. Adjust as needed. – Wiktor Stribiżew Commented Jun 14, 2016 at 11:37^(?!.*(?:01234|12345|23456|34567|45678|56789|67890|78901|89012|90123)).*$
can be used (with the^
and$
unnecessary in HTML5 pattern). – Wiktor Stribiżew Commented Jun 14, 2016 at 11:45