4

Hi I have some code on jquery validate rules validator.addMethod that allows the input to check for future date on card expiry date i.e. 10/2015 valid, what I would like to ask is there a way to add a limit of up to 20 years in the future, as at present they could enter card expiry date of 10/2099 or more. Thanks in advance!

Here is the code I have, it also needs a custom message. Exceeds date range

<input type="text" name="field_4"  id="field_4" value="">



 $.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 Expiry Date"
        );

        $(function() {

        $( "#Form" ).validate({
          rules: {    
            field_4: {
                required: true,
                Future: true,
                minlength: 7
                },
Sparky
  • 98,165
  • 25
  • 199
  • 285
Neil
  • 55
  • 2
  • 7

1 Answers1

8

One way:

function (value, element) {
    var today = new Date();
    var thisYear = today.getFullYear();
    var expMonth = +value.substr(0, 2);
    var expYear = +value.substr(3, 4);

    return (expMonth >= 1 
            && expMonth <= 12
            && (expYear >= thisYear && expYear < thisYear + 20)
            && (expYear == thisYear ? expMonth >= (today.getMonth() + 1) : true))
}
Alex K.
  • 171,639
  • 30
  • 264
  • 288