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.
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.");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With