Regular Expression to validate Sri Lankan National Identity Card numbers

Wed, 2019-02-13 16:51

I crafted a Regular Expression for Sri Lankan phone numbers before, and here is one to validate Sri Lankan National Identify Card numbers.

Regular Expression

PCRE

^(?:19|20)?\d{2}(?:[01235678]\d\d(?<!(?:000|500|36[7-9]|3[7-9]\d|86[7-9]|8[7-9]\d)))\d{4}(?i:v|x)$

JS flavor

^(?:19|20)?\d{2}(?:[01235678]\d\d(?<!(?:000|500|36[7-9]|3[7-9]\d|86[7-9]|8[7-9]\d)))\d{4}(?:[vVxX])$

Try it!



Requires a modern browser with ES2018 Regex support due to negative look-behinds.

Explanation

NIC numbers have 2 formats:

  1. 9 digits followed by an English character
  2. 11 digits followed by an English character

Pretty much everyone knows how the number is calculated, so I'm not going to explain it for the n+1-th time.

The above regex:

  1. Validates both new and old NIC number formats
  2. Correctly validates birth year to be in current or the last century
  3. Validates the possible number range for both male and female numbers (do not blame me for binary genders)
  4. Validates the last English letter, where it must be one of v or x that indicates the NIC holder is allowed to vote or not, respectively.