Hi, 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!
+2
A:
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.
Michael
2010-07-12 19:05:49
new Date(); returns DD/MM/YYYY correct? How do I parse out the "DD/" so it's just MM/YYYY and does this function check that the entered date is greater than the current date or just that the years are within 10?
Dirty Bird Design
2010-07-12 19:15:56
however you decide to pull the date parts out of the input field, hard-code a value in for the day (either 1 or 30). if you go for 30 and you want precise, then you will need to write a case statement for each month and adjust the number accordingly. I only did a simple difference on the dates so it is doing the actual dates, not just the years.
Michael
2010-07-12 19:25:14
A:
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: {
}
Dirty Bird Design
2010-07-12 20:04:37
A:
The answer is here at the bottom: http://forum.jquery.com/topic/credit-card-expiration-check
One short note: This linked code assumes your values for years are four digits. If your year values are two digits then you will need to convert them to four digits. Just use the following line where appropriate and all should be good.
var year = 2000+parseInt($year.val(), 10);
Haluk
2010-09-11 00:05:56