Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate credit card exp date with jQuery

I need help validating an input's value against the current date. Basically i need to "addMethod" for the jquery validate plug in that would require the CC Exp Date - format MM/YYYY to be a future date no more than 10 yrs into the future. I have been looking for 2 days and have yet to find a good solution! Please Help!

like image 293
Dirty Bird Design Avatar asked Dec 05 '25 07:12

Dirty Bird Design


2 Answers

With help from Patrick, this works and will hopefully help someone else out as well, this was a pain in the ass for a not so great programmer.

$.validator.addMethod(
"Future",
function (value, element) {
    var today = new Date();
    var startDate = new Date(today.getFullYear(),today.getMonth(),1,0,0,0,0);
    var expDate = value;
    var separatorIndex = expDate.indexOf('/');
    expDate = expDate.substr( 0, separatorIndex ) + '/1' + expDate.substr( separatorIndex );
    return Date.parse(startDate) <= Date.parse(expDate);
},
"Must be a valid Expiration Date."
);

then in rules: {
  elementName: {
    Future: true
  }
},
messages: {

}
like image 89
Dirty Bird Design Avatar answered Dec 07 '25 22:12

Dirty Bird Design


you can try something similar to this:

$.validator.addMethod('ccDate', function (value) {
        var inDate = new Date(value);
        var futureDate = new Date();
        futureDate.setYear(futureDate.getFullYear() + 10);
        var diff = inDate - futureDate;
        return (diff < 0);
    }, function() {
                    var $msg = 'Date must be within 10 years';  
                    return $msg;
        });

then just add a call to this new type (ccDate) for this field in your rules section of the validate call. you may have to tweak how you parse out the value of the field to create a proper date, but the idea is here.

like image 41
Michael Avatar answered Dec 07 '25 20:12

Michael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!