CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   Post a JavaScript (http://www.codingforums.com/forumdisplay.php?f=19)
-   -   Canadian Social Insurance Number SIN Validator (http://www.codingforums.com/showthread.php?t=279032)

Philip M 10-24-2012 10:13 AM

Canadian Social Insurance Number SIN Validator
 
Code:

<!DOCTYPE >

<html>
<head>
<title>Canadian Social Insurance Number Validation</title>
</head>

<script type="text/javascript">

// valid number examples 046-454-286  193-456-787  127-248-623

var sin = 0;

function validate(which,next) {
var val = which.value;
val = val.replace(/[^0-9]/g,"")
which.value = val;
next = "S" + next;
if (val.length == 3) {
document.getElementById(next).focus();
}
sin = document.getElementById("S1").value + document.getElementById("S2").value + document.getElementById("S3").value;
}

function CheckNumber(sin) {  // sin is a string value
var c = 0;

if (sin.substring(0,3) == "000") {
alert("Invalid SIN: SIN's can't start with 000.");
document.getElementById("S1").value = "";  // clear the fields
document.getElementById("S2").value = "";
document.getElementById("S3").value = "";
//document.getElementById("S1").focus();  // if required
return false;
}

if (sin.length !=9) {
alert ("You must complete all three fields!");
return false;
}

// odd digits
for (var i = 1; i<=9; i+=2) {
c += Number(sin.charAt(i-1));
}

// even digits
for (var i = 2; i <=8; i+=2) {
var digit = Number(sin.charAt(i-1)) *2;
if (digit >9) {digit = digit -9}
c += digit;
}

sin = document.getElementById("S1").value + "-" + document.getElementById("S2").value + "-" +document.getElementById("S3").value;

if ((c%10) == 0) {
alert ("The Social Insurance Number " + sin + " is valid");
}
else {
alert ("The Social Insurance Number " + sin + " is NOT valid");
return false;
}

}

</script>

</head>
<body>

Test numbers:- 046-454-286  193-456-787

<br><br>
Social Insurance Number <input type = "text" id = "S1" size =" 3" maxlength = "3" onkeyup = "validate(this,2)">
<input type = "text" id = "S2" size =" 3" maxlength = "3" onkeyup = "validate(this,3)">
<input type = "text" id = "S3" size =" 4" maxlength = "3" onkeyup = "validate(this,3)">
<br/><br/>
<input type="button" value="Validate Number" onclick="CheckNumber(sin)"/>

</body>

</html>



All times are GMT +1. The time now is 04:48 PM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.