最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regular expression for sequential numbers like 12345 or 456789 - Stack Overflow

programmeradmin1浏览0评论

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
  • stackoverflow.com/questions/32852339/… – Nagaraju Commented Jun 14, 2016 at 11:34
  • 1 /12345|23456|34567|45678|56789/ and add more as much as you want – YOU Commented Jun 14, 2016 at 11:37
  • 1 If you use HTML5 pattern attribute, use (?!(?:01234|12345|23456|34567|45678|56789|67890|78901|89012|90123)$).*. Adjust as needed. – Wiktor Stribiżew Commented Jun 14, 2016 at 11:37
  • @WiktorStribiżew's answer allows 123456 (and generally longer strings containing 5-digit sequences), but maybe that's OK – Chris Lear Commented Jun 14, 2016 at 11:43
  • 1 @ChrisLear: Yeah, no idea. OP says "5 digit" sequences, maybe 6 digit ones are allowed. If not, ^(?!.*(?: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
Add a comment  | 

2 Answers 2

Reset to default 20

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')

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');

发布评论

评论列表(0)

  1. 暂无评论