Deenee
asked on
Social Security number validation with JQuery
Hi, I need to add a method to the JQuery validation plugin. I have this piece of javascript code that I want to add into my JQuery validation. How do I do that?
<html>
<head>
<title>Check Norwegian NIN</title>
<script type="text/javascript">
function checkNIN(o) {
var nin = o.value;
if (nin.length != 11) {
return "must be 11 chars";
}
var cc0 = '0'.charAt(0);
var cw1 = [3, 7, 6, 1, 8, 9, 4, 5, 2];
var cw2 = [5, 4, 3, 2, 7, 6, 5, 4, 3, 2];
// check digit 1
var ws1 = 0;
for (var n=0; n<cw1.length; n++) {
ws1 += cw1[n] * (nin.charAt(n) - cc0);
}
var cd1 = 11 - (ws1 % 11);
if (cd1 == 10) {
return "invalid number, check digit 1 would be 10";
}
if (cd1 == 11) {
cd1 = 0;
}
if (nin.charAt(cw1.length) - cc0 != cd1) {
return "check digit 1 should be " + cd1;
}
// check digit 2
var ws2 = 0;
for (var n=0; n<cw2.length; n++) {
ws2 += cw2[n] * (nin.charAt(n) - cc0);
}
var cd2 = 11 - (ws2 % 11);
if (cd2 == 10) { // assuming this is needed
return "invalid number, check digit 2 would be 10";
}
if (cd2 == 11) {
cd2 = 0;
}
if (nin.charAt(cw2.length) - cc0 != cd2) {
return "check digit 2 should be " + cd2;
}
// check age
var century = -1, numyear = Number(nin.substr(4,2)), numindiv = Number(nin.substr(6,3));
if (numindiv > 499) {
if (numindiv < 750 && numyear >= 54) {
century = 18;
} else if (numyear < 40) {
century = 20;
} else if (numindiv = 900 && numyear >= 40) { // special cases
century = 19;
}
} else {
century = 19;
}
if (century == -1) {
return "invalid combination of year and individual number";
}
var check18 = new Date(century * 100 + numyear + 18, Number(nin.substr(2,2))-1, Number(nin.substr(0,2)), 0, 0, 0, 0);
alert (check18);
if (check18 > new Date()) {
return "Sorry, you have to be at least 18 to get registered";
}
return "ok!";
}
</script>
</head>
<body>
<form>
<input type="text" name="nin" maxlength="11" size="11" onkeyup="document.forms[0]['st'].value = checkNIN(this)">
<br><br>
<input type="text" name="st" readonly size="30">
</form>
</body>
</html>
line number 12-79 can be placed in a separate file and include that as plugin
ASKER
Hi. I want the code to work together with the validation plugin, because I have a range og other input elements in the form that already use the Jquery validator. I thought I would write it this way, and include the "jQuery.validator.addMetho d" sentence:
$ (document). ready (function () {
$ ("# formid"). validate ();
});
ASKER
Sorry, I did not see your first post..
For that you don't need plugin, just create a addMethod like this
http://stackoverflow.com/questions/241145/jquery-validate-plugin-how-to-create-a-simple-custom-rule
http://stackoverflow.com/questions/241145/jquery-validate-plugin-how-to-create-a-simple-custom-rule
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Open in new window