Skip to content

Instantly share code, notes, and snippets.

@henhan
Created April 13, 2016 13:52
Show Gist options
  • Save henhan/b751dbe1db5e70611134c524a578856c to your computer and use it in GitHub Desktop.
Save henhan/b751dbe1db5e70611134c524a578856c to your computer and use it in GitHub Desktop.
'use strict';
function isValid(id) {
// Make sure we have a string
id = '' + id;
if (id.match(/^[\-\s+\d]+$/) === null) {
return false;
}
// Remove all non digits
id = id.replace(/\D/g, '')
if (id.length !== 10 && id.length !== 12) {
return false;
}
if (id.length === 12) {
// Validate century prefix and reduce string that is to be validated to 10 digits
// Other prefixes than these indicate that it is a company
var prefix = parseInt(id.substring(0, 2));
if (prefix < 18 || prefix > 20) {
return false;
}
// Validate that year is not greater than current
var currentYear = (new Date()).getFullYear();
if (parseInt(id.substring(0, 4)) > currentYear) {
return false;
}
id = id.substring(2);
}
var sum = 0;
for (var i = 0; i < id.length; i++) {
var value = parseInt(id.charAt(i));
sum += getValidationValue(i, value);
}
return sum % 10 == 0;
}
function getValidationValue(index, baseValue) {
if (index % 2 !== 0) {
return baseValue;
}
var doubled = 2 * baseValue;
if (doubled < 10) {
return doubled;
} else {
return 1 + (doubled - 10);
}
}
var toTest = [
8209244113,
"8209244113",
"820924-4113",
"820924+4113",
"18820924-4113",
"19820924-4113",
"201302091077",
" 82 09 24 - 4113",
null,
"",
"8209244119",
"AA09244113",
"AA8209244113",
"820924B4113",
"17820924-4113",
"20820924-4113",
"201202091077",
" 82 09 24 _ 4014"
];
toTest.forEach(function(value) {
var ok = isValid(value);
console.log(value + " is valid: " + (ok ? 'true' : 'false'));
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment