简体   繁体   中英

jQuery validation depends rule not working

I'm working on a signup form and using jQuery validation to check the form. I want to validate the day of birth so that they can't select for example day 31 for february. My code is:

birthday:  {
             required: true,
             min: 1,
             max: {
             depends: function(element) {
              switch (parseInt($('#birthmonth').val())){
                     case 2:
                            maxday = 29;
                            break;
                     case 4:
                     case 6:
                     case 9:
                     case 11:
                            maxday = 30;
                            break;
                     default:
                            maxday = 31;                                
                 }                                                
              return maxday;
                 }}
            },

The switch is working and the function returns the correct value for each month, but the validation still shows invalid selection even when I select any month then day 7. I tried to convert back the return value to string, but it's still not working.

This would work out a little better for you inside of a custom method. Create your new rule by using the addMethod method .

$(document).ready(function () {

    $('#myform').validate({
        rules: {
            birthday: {
                required: true,
                min: 1,
                mymax: ['#birthmonth']
            }
        }
    });

    jQuery.validator.addMethod('mymax', function (value, element, params) {
        switch (parseInt($(params[0]).val())) {
            case 2:
                maxday = 29;
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                maxday = 30;
                break;
            default:
                maxday = 31;
        }
        params[1] = maxday;  // simply used for populating message at {1}
        return parseInt(value) <= maxday;
    }, "Please enter a value less than or equal to {1}");

});

Working DEMO: http://jsfiddle.net/4Uv8Y/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM