Skip to content

Instantly share code, notes, and snippets.

@rordi
Last active July 31, 2020 12:35
Show Gist options
  • Save rordi/e6445c0927da635750f93532a0c6c320 to your computer and use it in GitHub Desktop.
Save rordi/e6445c0927da635750f93532a0c6c320 to your computer and use it in GitHub Desktop.
Javascript-based validation of Swiss AHV numbers AHVN13 / EAN13 [Validierung von Schweizer AHV Nummern mit Javascript]
/**
* Javascript-based validation of Swiss AHV numbers AHVN13 / EAN13
* [Validierung von Schweizer AHV Nummern mit Javascript]
*/
var inp = document.getElementById('ahvn13');
inp.addEventListener('change', _validateAhvn13);
var _validateAhvn13 = function(input) {
var pattern = /^756\.(\d{4})\.(\d{4})\.(\d{2})$/; // format is 756.0000.0000.00
var inp = input.target;
if(!inp.value.match(pattern)) {
inp.setCustomValidity('Wrong format. Expected format: 756.0000.0000.00');
} else {
if(_computeAhvn13CheckDigit(inp.value) != parseInt(inp.value.substr(-1))) {
inp.setCustomValidity('Number not valid');
} else {
inp.setCustomValidity('');
}
}
}
var _computeAhvn13CheckDigit = function(ahvn13str)
{
// EAN13: remove non-digits, remove last character, reverse the order of the string
var ahvn13str = ahvn13str.replace(/\D/g,'');
chars = ahvn13str.substring(0, ahvn13str.length-1).split("").reverse();
// EAN13: first + second * 3 + third + fourth * 3 etc.
var crosssum = 0;
for(i = 0; i < chars.length; i++) {
if(0 == i % 2 ) { // even
crosssum += parseInt(chars[i]) * 3;
} else { // odd
crosssum += parseInt(chars[i]);
}
}
// EAN13: checkdigit is the difference of crosssum to the next multiple of 10
return (10 - (crosssum % 10));
}
@rordi
Copy link
Author

rordi commented Jul 31, 2020

Sorry. You may try without the reverse(). I am not sure that this step is necessary according to EAN-13 standard.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment