JavaScript Examples

Validation of a Canadian Social Insurance Number (SIN)

The Canadian Social Insurance Number is a unique 9-digit number issued to all permanent residents of Canada. A lot of personal information is cross-linked to this number. Thus it is vital that whenever the number is required, there should be no transcription errors.

Errors are minimized by the use of a check digit, namely the last digit is used to complement the properties of the preceding digits. The validation may be carried out as follows:

The following form validates the SIN entered by user.

Enter your social insurance number: - -
  
RESULT:
The JavaScript code is as follows:
function Pad(N){
    // Pad adds leading zeroes to each group of 3 digits
    l=N.length;
    if(l==1)return N+"00";
    else if(l==2)return N+"0";
    else return N;
}
function Double(c){
    // calculates each of the doubled even digits
    n=eval(c)*2;
    if(n>9)n=n-9;
    return n;
}
function DisplaySin(){
    // displays number in legible form
    s1=document.sin.sin1.value;
    s2=document.sin.sin2.value;
    s3=document.sin.sin3.value;
    return s1+"-"+s2+"-"+s3;
}
function Validate(){
    // function called OnClick of button Validate
    s=document.sin.sin1.value+document.sin.sin2.value+document.sin.sin3.value;
    sum=eval(s.substr(0,1));
    sum+=Double(eval(s.substr(1,1)));
    sum+=eval(s.substr(2,1));
    sum+=Double(eval(s.substr(3,1)));
    sum+=eval(s.substr(4,1));
    sum+=Double(eval(s.substr(5,1)));
    sum+=eval(s.substr(6,1));
    sum+=Double(eval(s.substr(7,1)));
    sum+=eval(s.substr(8,1));
    if(sum%10==0)return DisplaySin()+" is a valid number";
    else return DisplaySin()+" is NOT a valid number";
}