Regex to validate document - Javascript

Asked

Viewed 133 times

0

I’m having some problems validating the document.

Previously I asked this question here: Regex to validate national document number

The problem I’m having is that the user is typing sequential or equal numbers, for example:

  • 000000000
  • 111111111

until

  • 999999999

and also things like:

  • 1234567890
  • 0987654321
  • 123123123
  • 456456456
  • abc123

And it’s giving me a big problem. I need, regex, to validate numbers and letters, or just numbers, without being sequential, without being equal, without being 'abc' or things like that, without special characters, without spaces. An example of correct and incorrect validation:

  • 90956780083 - true
  • PR213328112 - true
  • 00000000000 - false
  • 0000 - false
  • 123456789 - false
  • 1234 - false
  • abc123 - false
  • 456456 - false
  • 987654321 - false
  • 3210 - false
  • çá058 - false
  • PR 213328112 - false
  • PR.213328112 - false

Well, follow the regex I got:

console.log(/(?=.*\d)[A-Za-z0-9]{1,}/g.test('abc1234')); // somente números e letras ou somente números
 console.log(/(?!(\d)\1{3})\d{1,}/g.test('11111')); // numeros iguais (deveria ser false mas retorna true)
// falta o regex para números sequencias e letras sequeciais que não entendi como funciona. 

  • What’s your big problem, it’s not clear to me. Don’t you want the same digits to appear? They all have to be different?

  • I edited the question, I think it’s now a little clearer

  • ^(\d) 1{2,10} to match repeated numbers can use this.

  • Instead of {1,}, you can use +, which is the same thing (one or more occurrences). And the part of checking sequential numbers I find it easier to loop. With regex is even possible, but I don’t think it’s worth the hassle.

1 answer

2


See the demo of the Regex101:

Regex101

With the examples given the following regular expression can be used: ^(?!(\d)\1{10,})(?=.*\d)[A-Za-z0-9]{11}

You were already trying to use the Negative Lookahead ?! to solve this problem, but in two different expressions and the wrong way. It is possible to solve this only with one expression.

With the use of \1 which corresponds to repeated strings of the first capture group (\d), and the quantifier {10,} with a repetition number greater than 10.

And the quantifier of another answer that is {1,11}, that is, from 1 to 11 characters, must be changed to {11}, only 11 characters.

In the part of sequential numbers, as @hkotsubo said, regular expression is not necessary for this... But you can create something to verify the presence of 123456789 or other Negative Lookahead

  • Thank you so much! I made some changes and it was great!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.