Regular Expressions – validating the NIC number


Regular expressions!!! kind of a scary thing for most developers.. πŸ™‚ Well it is scary because its not something that is really user friendly for developers, its a combination of letters, special characters and numbers that kind of make our eyes go the wrong way when we look at them.

Well I normallyΒ don’tΒ like to use regular expressions, I just copy from some web site and paste the regular expression when I really need to use one. But I needed to learn how to build my own regular expression and I couldn’t find one on the Internet. What a bummer that was πŸ™‚

What I wanted to do was to validate a National Identity Card (NIC) number (Sri Lankan). Which is 9 number followed by one letter that is v, V, x or X.

So how to write the regular expression for this?

Well you start with

/^

that means that the regular expression is started.

Now we need to tell them that next nine characters should be numbers,

[0-9]

that is how you say numbers πŸ™‚ , how to tell them that next 9 digits are numbers???

[0-9]{9}

the number in curly brackets is the number of times to repeat.

Next we need to tell the regular expression that next letter should be x, X, v or V.

[xXvV]

and then we need to tell that the regular expression is over. you do that by,

$/

The final version of the regular expression for validating the NIC number is,

/^[0-9]{9}[vVxX]$/

It is really easy when you break it down like that. πŸ˜€

Advertisements

17 thoughts on “Regular Expressions – validating the NIC number

  1. ishan

    didnt work with mine 😦 im working on c#. so if i do like below that should work or am i doing i wrong?

    if (Regex.IsMatch(someTextBox.Text, @”/^[0-9]{9}[vVxX]$/”))
    do something;

    Reply
    1. surendias Post author

      Hi Ishan,

      I used this with java. I’m not really sure how to use it in C#. If the syntax is correct for the string matching then the regular expression should be the same.

      Reply
  2. choolani abegunawardhana

    please explain me how to use above expression in Javascript. can we use like below,
    var RegExp= ^/[0-9]{9}[vVxX]$/
    if((!RegExp.test(q_6nicNumber)){
    alert(“Please enter a valid id number”);
    return false;
    }

    Reply

Let me know what you think .. :)

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s