So was having a bit of issue trying to find a JS code that would do exactly what I wanted to do, which was to ignore all spaces and non-numerical characters as well as to validating on tabbing to a new field. It alerts if the ABN is invalid and refocuses & resets the field to empty.
Weights = new Array(10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19);
function ABNValidate() {
ABN = document.getElementById('abn').value; //grabs data from ABN field
ABN=ABN.replace(/\D/g,'');
frst2chars=ABN.slice(0,2)-10;
rest=ABN.slice(2,11);
newABN=frst2chars+rest;
total = 0;
for (i=0; i < newABN.length; i++) {
total += Weights[i]*newABN.charAt(i);
}
if (ABN.length == 0) {
return true;
} else if (ABN.length != 11) {
alert("ABN should contain exactly 11 characters!");
setTimeout(function() {
document.getElementById('abn').focus();
}, 0);
return false;
} else if (total == 0 || total % 89 != 0) {
alert(ABN+" is an invalid ABN!");
setTimeout(function() {
document.getElementById('abn').value=''; //resets field to empty
document.getElementById('abn').focus(); //refocuses back to field after alert
}, 0);
return false;
} else {
return true;
}
}
Nice Post
ReplyDelete