Last active
January 6, 2024 09:19
-
-
Save star26bsd/6d044e17d090949ad062d1f8dc8ba2a2 to your computer and use it in GitHub Desktop.
JavaScript function to validate the Swiss AHV number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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