JS to run a validation in a form
I have added a JS for validation of a field included in a form (Luhn algorithm). I'm told the script is ok. But nothing happens if I type in a wrong number. Have a missed something? Total newbie to JS 😞

I have added a JS for validation of a field included in a form (Luhn algorithm). I'm told the script is ok. But nothing happens if I type in a wrong number. Have a missed something? Total newbie to JS 😞

Assuming this function is correct (I did not verify it and when I used a sample "correct" number from the Wiki page for Luhn algorithm it returned false, so use it at your own risk...), you can use this code as the custom validation script of your field:
if (event.value) {
var result = validatePersonnummer(event.value);
if (result==false) {
app.alert("Invalid number!");
event.rc = false;
}
}
function validatePersonnummer(input) {
// Check valid length & form
if (!input) return false;
if (input.indexOf('-') == -1) {
if (input.length === 10) {
input = input.slice(0, 6) + "-" + input.slice(6);
} else {
input = input.slice(0, 😎 + "-" + input.slice(8);
}
}
if (!input.match(/^(\d{2})(\d{2})(\d{2})\-(\d{4})|(\d{4})(\d{2})(\d{2})\-(\d{4})$/)) return false;
// Clean input
input = input.replace('-', '');
if (input.length == 12) {
input = input.substring(2);
}
// Declare variables
var d = new Date(((!!RegExp.$1) ? RegExp.$1 : RegExp.$5), (((!!RegExp.$2) ? RegExp.$2 : RegExp.$6)-1), ((!!RegExp.$3) ? RegExp.$3 : RegExp.$7)),
sum = 0,
numdigits = input.length,
parity = numdigits % 2,
i,
digit;
// Check valid date
if (Object.prototype.toString.call(d) !== "[object Date]" || isNaN(d.getTime())) return false;
// Check luhn algorithm
for (i = 0; i < numdigits; i = i + 1) {
digit = parseInt(input.charAt(i))
if (i % 2 == parity) digit *= 2;
if (digit > 9) digit -= 9;
sum += digit;
}
return (sum % 10) == 0;
};
Already have an account? Login
Enter your E-mail address. We'll send you an e-mail with instructions to reset your password.