Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Validator Credit Card Number + Type Match

Trying to add a customer jQuery validator method that basically checks the card type and the credit card number for validity.

ie. If the type is MasterCard, if the card number doesn't start with 5, it's invalid or if the type is Visa, if the card number doesn't start with 4, it's invalid. My company only charges MC or Visa, so no others are needed.

$.validator.addMethod("CCNumber", function(value, element, param) {
  if (param == "MasterCard") {
    return value.substring(0,1) != 5;   
  }
  else if (param == "Visa") {
    return value.substring(0,1) != 4;   
  }
});

Calling it here:

cardnumber: {
  required: true,
  creditcard: true,
  minlength: 13,
  maxlength: 16,
  digits: true,
  CCNumber: function(){ return $('#cardtype').val(); }
},

And the message...

cardnumber: {
  required: "Please enter a valid credit card number",
  minlength: "Please enter a valid credit card number",
  maxlength: "Please enter a valid credit card number",
  digits: "Your credit card number cannot contain spaces.",
  CCNumber: "WRONG"
},

Finally, the HTML:

<select name="cardtype" id="cardtype">
  <option value="MasterCard">MasterCard</option>
  <option value="Visa">Visa</option>
</select>

I've never written a jQuery method before, but nothing is happening here. I'm not entirely sure what I've done wrong, as I've tried to look at other methods, but couldn't find anything.

like image 351
jsquadrilla Avatar asked Nov 13 '22 15:11

jsquadrilla


1 Answers

The jQuery Validation plugin already has additional methods available for things like this.

The following is the default method used in the "Additional Methods" file, but then edited down for only Visa & Mastercard.

jQuery.validator.addMethod("creditcardtypes", function(value, element, param) {
    if (/[^0-9-]+/.test(value)) {
        return false;
    }

    value = value.replace(/\D/g, "");

    var validTypes = 0x0000;

    if (param.mastercard)
        validTypes |= 0x0001;
    if (param.visa)
        validTypes |= 0x0002;

    if (validTypes & 0x0001 && /^(5[12345])/.test(value)) { //mastercard
        return value.length == 16;
    }
    if (validTypes & 0x0002 && /^(4)/.test(value)) { //visa
        return value.length == 16;
    }
    return false;
}, "Please enter a valid credit card number.");
like image 54
Sparky Avatar answered Nov 15 '22 05:11

Sparky