Dirty Bird Design
Dirty Bird Design

Reputation: 5553

jQuery validate credit card exp date as future date

I can't seem to get this right, I can get it to catch a past date, but not return true on future date.I just need to validate my form's Credit Card Expiration Date as being in the future, this isn't working, any ideas? the date has to be in the format MM/YYYY with a "/" in between them.

$.validator.addMethod(
"FutureDate",
function(value, element) {
    var startdatevalue = (.getMonth/.getYear);
    return Date.parse(startdatevalue) < Date.parse($("#ExpirationDate").val());
}, 
    "End Date should be greater than Start Date."
);

Upvotes: 2

Views: 2289

Answers (1)

user113716
user113716

Reputation: 322622

You're not actually getting it to catch a past date. If you're passing a date like this "11/2010" to your Date.parse(), it is returning NaN (or Not a Number) which is the logical equivalent to returning false.

Try doing this to see what I mean:

alert( Date.parse('11/2010') );

If you add a day number, it should work. Something like:

var startdatevalue = '11/1/2010';

Of course, this example uses a hard coded date. If the values are stored as 11/2010, you could try something like this:

    // Get the index of the "/"
var separatorIndex = value.indexOf('/');

    // Add "/1" before the separatorIndex so we end up with MM/1/YYYY
var startDate = value.substr( 0, separatorIndex ) + '/1' + value.substr( separatorIndex );

    // Do the same with the expiration date
var expDate = $("#ExpirationDate").val();
separatorIndex = expDate.indexOf('/');
expDate = expDate.substr( 0, separatorIndex ) + '/1' + expDate.substr( separatorIndex );

    // Return the comparison
return Date.parse(startDate) < Date.parse(expDate);

Upvotes: 1

Related Questions