Skip to content

Instantly share code, notes, and snippets.

@star26bsd
Last active January 6, 2024 09:19
Show Gist options
  • Save star26bsd/6d044e17d090949ad062d1f8dc8ba2a2 to your computer and use it in GitHub Desktop.
Save star26bsd/6d044e17d090949ad062d1f8dc8ba2a2 to your computer and use it in GitHub Desktop.
JavaScript function to validate the Swiss AHV number
// Documentation: https://www.sozialversicherungsnummer.ch/aufbau-neu.htm
function isValidAHVNumber(ahvNumber) {
// Remove dots from the AHV number
let cleanedAhvNumber = ahvNumber.replace(/\./g, '');
if (!/^\d{13}$/.test(cleanedAhvNumber)) {
return false; // Checks if the AHV number is exactly 13 digits after removing dots
}
if (cleanedAhvNumber.substring(0, 3) !== '756') {
return false; // Checks the country code
}
// Calculate the check digit using the EAN13 algorithm
let sum = 0;
for (let i = 11; i >= 0; i--) {
let factor = (11 - i) % 2 === 0 ? 3 : 1;
sum += parseInt(cleanedAhvNumber[i]) * factor;
}
let checkDigit = (10 - (sum % 10)) % 10;
// Compare calculated check digit with the last digit of cleaned AHV number
return checkDigit === parseInt(cleanedAhvNumber[12]);
}
// Example usage
document.getElementById('ahv_field').addEventListener('input', function() {
let errorMessage = document.getElementById('ahv-error-message');
if (!isValidAHVNumber(this.value)) {
errorMessage.style.display = 'block';
} else {
errorMessage.style.display = 'none';
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment