Regex to validate national document number

2

I'm trying to create a national document validator that accepts numbers and letters or just an 11-character JavaScript limit number.

The problem is with regex creation.

Follow 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

Here's an example in JSFiddle: JSFiddle

    
asked by anonymous 17.10.2018 / 11:05

1 answer

7

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

Where 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} - Corresponds from 1 to 11 characters of A to Z or a to z or 0 to 9 . No special characters are allowed.

Another case

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

Without checking for at least one digit.

    
17.10.2018 / 13:30