Skip to content

Instantly share code, notes, and snippets.

@kandros
Created September 4, 2015 10:59
Show Gist options
  • Save kandros/e947afe32777b6b098c8 to your computer and use it in GitHub Desktop.
Save kandros/e947afe32777b6b098c8 to your computer and use it in GitHub Desktop.
Javascript Regon validator
function validateRegon (regon) {
//REGON is a 9 or 14 digit number. Last digit is control digit from equation:
// [ sum from 1 to (9 or 14) (x[i]*w[i]) ] mod 11; where x[i] is pointed NIP digit and w[i] is pointed digit
//from [8 9 2 3 4 5 6 7] for 9 and [2 4 8 5 0 9 7 3 6 1 2 4 8] for 14 digits.
var n = regon.length;
var w;
var cd = 0; // Control digit (last digit)
var isOnlyDigit = /^\d+$/.test(regon);
if ( n !==9 && n !== 14 && !isOnlyDigit) {
console.log("Error");
return false;
}
if ( n === 9) {
w = [8, 9, 2, 3, 4, 5, 6, 7];
} else {
w = [2, 4, 8, 5, 0, 9, 7, 3, 6, 1, 2, 4, 8];
}
for (var i = 0; i<n-1; i++) {
cd += w[i]*parseInt(regon.charAt(i));
}
cd %= 11;
if ( cd === 10 ) {
cd = 0;
}
if ( cd !== parseInt(regon.charAt(n-1)) ) {
console.log("Not valid");
return false;
} else {
console.log("Valid!");
}
}
// validateRegon("999999999"); // 9 digit
// validateRegon("99999999999999"); // 14 digit
// validateRegon("793769692"); // valid 9 digits Regon
// validateRegon("63867185528390"); //valid 14 digits Regon
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment