Forums

Credit Card No. Validation with Luhn algorithm

iaweb2 25 Sep, 2017
I need to validate the entered number into a Credit Card field with the Luhn algorithm and javascript. I have the JavaScript loaded into the form under Load JavaScript in the Setup Tab of the Form under the onLoad area as follows:

  var cc_number_saved = "";

function checkLuhn(input)
{
  var sum = 0;
  var numdigits = input.length;
  var parity = numdigits % 2;
  for(var i=0; i < numdigits; i++) {
    var digit = parseInt(input.charAt(i))
    if(i % 2 == parity) digit *= 2;
    if(digit > 9) digit -= 9;
    sum += digit;
  }
  return (sum % 10) == 0;
}


It seems to properly load into the form as it shows up properly in the form in the frontend when I look at the source code. The problem is I am not sure how to load the actual validation of the field within the form now... in a regular html form I would do it like this:
<input type="text" size="24" maxlength="20" name="cc_number" onblur="
  // save input string and strip out non-numbers
  cc_number_saved = this.value;
  this.value = this.value.replace(/[^\d]/g, '');
  if(!checkLuhn(this.value)) {
    alert('Sorry, that is not a valid number - please try again!');
    this.value = '';
  }
" onfocus="
  // restore saved string
  if(this.value != cc_number_saved) this.value = cc_number_saved;
">


My problem is, how do I get this into the field in Chronoforms5??

Anybody can guide me on this please?

Thank you,


Heiko
GreyHead 26 Sep, 2017
Hi Heiko,

IN CFv5 you can define a validation function and call that with the Custom validation option in the input. That should work OK. The only problem is that it is called On Submit and not necessarily On Blur.

I have successfully used the Stripe jQuery.payment library in the past to do CC validation. It worked very well and did not require Stripe. I see that the library is now deprecated but still available.

Bob
iaweb2 26 Sep, 2017
Thanks Bob for the answer, I saw the Stripe library and tried to implement it, but because of the depreciation half the functions do not work anymore and I get an array error, that's why I wanted to use the standard Luhn algorithm...

Heiko
This topic is locked and no more replies can be posted.