jQuery Validation: Changing Rules Dynamically

后端 未结 10 936
栀梦
栀梦 2020-12-07 13:07

I have a single form that, depending on which radio button is clicked (Login or Signup), displays either:

  • email address
  • password

or:

10条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-07 13:47

    I had a similar problem and solved it by adding a "requiredForLogin" class to all of the login textboxes, and "requiredForSignUp" class to all of the signup textboxes.

    Then used jQuery's toggleClass, and jQuery.validate's addClassRules to turn on and off the rules depending on which button was pressed.

    function EnableAllValidation() {
        // remove the jquery validate error class from anything currently in error
        //  feels hackish, might be a better way to do this
        $(".error").not("label").removeClass("error");
    
        // remove any the 'disabled' validation classes, 
        //  and turn on all required validation classes 
        //  (so we can subsequently remove the ones not needed)
        $(".requiredForLoginDisabled").toggleClass("requiredForLoginDisabled requiredForLogin");
        $(".requiredForSignUpDisabled").toggleClass("requiredForSignUpDisabled requiredForSignUp");
    }
    function EnableLoginValidation() {
        // reenable all validations
        //  then disable the signUp validations
        EnableAllValidation();
        $(".requiredForSignUp").toggleClass("requiredForSignUpDisabled requiredForSignUp");
    }
    function EnableSignUpValidation() {
        // reenable all validations
        //  then disable the login validations
        EnableAllValidation();
        $(".requiredForLogin").toggleClass("requiredForLoginDisabled requiredForLogin");
    }
    $(document).ready(function () {
        $("input[value='login']").click(function () {
            EnableLoginValidation();
        });
        $("input[value='signup']").click(function () {
            EnableSignUpValidation();
        });
    
        $("#myForm").validate();
        jQuery.validator.addClassRules({
            requiredForSignUp: {
                required: true
            },
            requiredForLogin: {
                required: true
            }
        });
    
    });
    

提交回复
热议问题