'Regular expression for sequential numbers like 12345 or 456789
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}$/;
Solution 1:[1]
It 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')
Solution 2:[2]
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');
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Narendra Yadala |
Solution 2 |