Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Validate Credit Card Expiry Date in Rules addMethod Limit 20 Years in Future

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
                },
like image 468
Neil Avatar asked Feb 12 '23 15:02

Neil


1 Answers

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))
}
like image 181
Alex K. Avatar answered Apr 08 '23 09:04

Alex K.