Hi all!
I recently started using Formidable forms, I am creating a website for a financial company specializing in consumer loans.
I am in the process of creating an application form. One of the requirements is for the applicant to enter his/her SIN (Social Insurance Number.) All SIN's use the Luhn Algorith in order to validate the authenticity of the number.
I would like to add custom JS in order to ensure that each each SIN will be legit, I found a sample code online but I am unsure how I could get a version of it to be compatible with Formidable.
<script>
// Javascript program to implement Luhn algorithm
// Returns true if given
// card number is valid
function
checkLuhn(cardNo)
{
let nDigits = cardNo.length;
let nSum = 0;
let isSecond =
false
;
for
(let i = nDigits - 1; i >= 0; i--)
{
let d = cardNo[i].charCodeAt() -
'0'
.charCodeAt();
if
(isSecond ==
true
)
d = d * 2;
// We add two digits to handle
// cases that make two digits
// after doubling
nSum += parseInt(d / 10, 10);
nSum += d % 10;
isSecond = !isSecond;
}
return
(nSum % 10 == 0);
}
let cardNo =
"79927398713"
;
if
(checkLuhn(cardNo))
document.write(
"This is a valid card"
);
else
document.write(
"This is not a valid card"
);
</script>
Hoping someone could assist me with this! I spoke to support and they recommended I make a post here.
This should be as simple as replacing:
let cardNo = "79927398713";
With something like:
let cardNo = $("#field_FIELDKEYHERE").val();
Reference: https://formidableforms.com/knowledgebase/javascript-examples/#kb-referencing-field-types
Before you use the $() notation, you have to convert this script to jQuery otherwise the $ will give you an error. The JavaScript equivalent to the $() is get_element_by_id()
Hi Bobby, Thank you for your reply.
I followed your directions but it does not seem to be working and I can feel I am missing something here. This is the code I am using in the Customize HTML form settings.
// Javascript program to implement Luhn algorithm
// Returns true if given
// card number is valid
function checkLuhn(cardNo)
{
let nDigits = cardNo.length;
let nSum = 0;
let isSecond = false;
for (let i = nDigits - 1; i >= 0; i--)
{
let d = cardNo[i].charCodeAt() - '0'.charCodeAt();
if (isSecond == true)
d = d * 2;
// We add two digits to handle
// cases that make two digits
// after doubling
nSum += parseInt(d / 10, 10);
nSum += d % 10;
isSecond = !isSecond;
}
return (nSum % 10 == 0);
}
let cardNo = "get_element_by_id("#field_[81]").val();";
if (checkLuhn(cardNo))
document.write("This is a valid card");
else
document.write("This is not a valid card");
This code is under the HTML code for the field.
Could be a few things. First off though, you've listed a field ID in brackets. You need to get the field key and then no brackets would surround that value.
Something like:
let cardNo = "get_element_by_id("#field_js2dlv").val();
Please login or Register to submit your answer