Regex to validate national document number

Asked

Viewed 1,913 times

2

I am trying to create a national document validator that accepts numbers and letters or only number with 11 characters limit in Javascript.

The problem is in the creation of regex.

Follows the code:

var documento = 'abc123-$/';
alert(documento.replace(/^[A-Za-z0-9]{0,5}\d+[A-Za-z0-9]{0,6}$g/,"")); // resultado deveria ser: abc123

var documento = 'abcdef-$/';
alert(documento.replace(/^[A-Za-z0-9]{0,5}\d+[A-Za-z0-9]{0,6}$g/,"")); // resultado deveria ser vazio porque deve conter pelo menos 1 número

Follow an example in Jsfiddle: Jsfiddle

  • In the case of documents, I think it would be better to do the calculation of the digit(s) (s) verifier(s), that they usually have (find out what is the calculation of the document you are working on and implement it). Although regex "works", not every 11-digit/letter string will be a valid document if it has checker digits - and in this case the calculation of these already ensures that the document number is valid, making regex unnecessary.

  • That’s kind of impossible because I’m using a field for all the national documents. It is a system of sale of tickets online, it is necessary only that the user fill out a document with photo, can be from work card to AOB card in the same field.

1 answer

6


Use this regular expression: (?=.*\d)[A-Za-z0-9]{1,11}

In which the demo on Regex101 can be seen.

Explanation

  • (?=.*\d) - Positive Lookahead, which ensures that at least one number is present in the string.
  • [A-Za-z0-9]{1,11} - Matches 1 to 11 characters from A to Z or of a to z or of 0 to 9. So no special characters allowed.

Another case

If numbers or letters only 1 to 11 characters, use the following regular expression: [A-Za-z0-9]{1,11}

Without the part of checking if there is at least one digit.

Browser other questions tagged

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