jQuery Validation: Changing Rules Dynamically

后端 未结 10 856
栀梦
栀梦 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
            }
        });
    
    });
    
    0 讨论(0)
  • 2020-12-07 13:48

    Take a look at my answer https://stackoverflow.com/a/20547836/1399001. It includes a working jsfiddle. In your example will be something like this:

    $("input[name='userAction']").change(function() {
    
        var settings = $("#myForm").validate().settings;
    
          if ($("input[name='userAction']:checked" ).val() === "login") {
                $.extend(settings, {
                  rules: loginRules
                });
        } else {
                $.extend(settings, {
                  rules: signupRules
                });
        }
    
    
        $("#myForm").valid();
    
    });
    
    0 讨论(0)
  • 2020-12-07 13:54

    Or you can use the depends property.

    http://jqueryvalidation.org/category/plugin/ search for depends

    Example: Specifies a contact element as required and as email address, the latter depending on a checkbox being checked for contact via email.

    $(".selector").validate({
      rules: {
        contact: {
          required: true,
          email: {
            depends: function(element) {
              return $("#contactform_email:checked")
            }
          }
        }
      }
    });
    
    0 讨论(0)
  • 2020-12-07 13:54

    try this..

    rules: {
        address: {
           required: {
                       depends: function(element) {
                         if (....){
                           return true;}
                         else{
                           return false;}
                       }
                     }
                 }
           }
    

    credit from here.

    0 讨论(0)
  • 2020-12-07 13:54

    Keep track of the validation object and remove/replace rules directly. Works for me with v1.13.0

    var validation = $('#form1').validate(); //Keep track of validation object
    
    //Rule set 1
    var validationRulesLogin = {
        headerEmail: {
            required: true,
            email: true
        },
        headerPassword: "required"
    };
    var validationMessagesLogin = {
        headerEmail: {
            required: "Please enter your email address.",
            email: "Not a valid email address."
        },
        headerPassword: "Please enter your password."
    };
    
    //Rule set 2
    var validationRulesSignup = {
        signupEmail: {
            required: true,
            email: true
        },
        signupPassword: "required",
        signupPassword2: {
            equalTo: "#phBody_txtNewPassword"
        }
    };
    var validationMessagesSignup = {
        signupEmail: {
            required: "Please enter your email address.",
            email: "Not a valid email address."
        },
        signupPassword: "Please enter your password.",
        signupPassword2: "Passwords are not the same."
    };
    
    //Toggle rule sets
    function validatingLoginForm(){
        validation.resetForm();
        validation.settings.rules = validationRulesLogin;
        validation.settings.messages = validationMessagesLogin;
    }
    function validationSignupForm(){
        validation.resetForm();
        validation.settings.rules = validationRulesSignup;
        validation.settings.messages = validationMessagesSignup;
    }
    
    0 讨论(0)
  • 2020-12-07 14:00

    the below code is working superb...

    .validate({
      ignore: ":not(:visible),:disabled",
      ...
    
    0 讨论(0)
提交回复
热议问题