Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Client-side validation of credit cards

Does anyone have a library or JavaScript snippet to validate the check digit of credit cards before the user hits Submit?

like image 919
James Avatar asked Nov 01 '08 02:11

James


3 Answers

The jQuery Validation Plugin has a method for validating credit card numbers.

There are other specific scripts:

  • JavaScript Credit Card Validation Function
  • Credit Card Validation

Most of them use the Luhn algorithm.

like image 148
Christian C. Salvadó Avatar answered Oct 23 '22 09:10

Christian C. Salvadó


Probably OP doesn't even follow this thread anymore but this may be helpful for someone else:

http://jquerycreditcardvalidator.com

It checks the card type, validates its length and checks for mod 10 with Luhn algorithm.

like image 35
Engin Yapici Avatar answered Oct 23 '22 10:10

Engin Yapici


You can use this snippet to validate 16 digits card numbers with Luhn algorithm:

function validateCardNumber(number) {
    var regex = new RegExp("^[0-9]{16}$");
    if (!regex.test(number))
        return false;

    return luhnCheck(number);
}

function luhnCheck(val) {
    var sum = 0;
    for (var i = 0; i < val.length; i++) {
        var intVal = parseInt(val.substr(i, 1));
        if (i % 2 == 0) {
            intVal *= 2;
            if (intVal > 9) {
                intVal = 1 + (intVal % 10);
            }
        }
        sum += intVal;
    }
    return (sum % 10) == 0;
}
like image 22
alexey Avatar answered Oct 23 '22 09:10

alexey