Friday 15 November 2013

Canadian Sin Regex

Regex is a two fold problem:

  • the first is that you have a problem
  • the second is that your problem can be solved using regex

What do I mean by this? well regex is one of those things that you're not going to use very often so it's not really worth the effort to learn it 100% but just enough to get what you need done and forget it by the time you need it again, much like calculus.

Anyway this is a pretty solid site to find what you need Regex Library.

but this is what I use to verify a Canadian sin "^\d{3}(\s?|[-]?)\d{3}(\s?|[-]?)\d{3}$"

It's got you covered for 123123123, 123 123 123, 123-123-123

to use it with an input box use a combination of the pattern and title attributes

<input id = "SIN_TXT" name="SIN_TXT" type ="text" title="6 digit Canadain Social Insurence Number"  pattern="^\d{3}(\s?|[-]?)\d{3}(\s?|[-]?)\d{3}$" placeholder="### ### ###" />

if you are a poor soul that has to support a lower end browser such as ie8 then attach it using javascript

function validateSIN(sinString)
    var sinPattern = /^\d{3}(\s?|[-]?)\d{3}(\s?|[-]?)\d{3}$/;
    return sinPattern.test(sinString);

Now that you've validated that the user is submitting a 9 digit number, lets confirm that it is in fact a SIN and not just 9 random digits, check out this Validate Sin Number.

here's the algorithm I use:

function verifySIN(SIN) {
    var sinArray = SIN.replace(/\W/g, '')
    var t = 0;
    if (sinArray.length != 9)
        return false;

    for (x in sinArray) {
        var p = 0;
        t += (p = (x % 2 + 1) * sinArray[x]) > 9 ? (p + (p % 10 * 9)) / 10 : p;

    return t % 10 === 0;