jQuery 验证:动态更改规则

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4128657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:43:23  来源:igfitidea点击:

jQuery Validation: Changing Rules Dynamically

jqueryjquery-validate

提问by Bullines

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

我有一个表单,根据单击的单选按钮(登录或注册),它会显示:

  • email address
  • password
  • 电子邮件地址
  • 密码

or:

或者:

  • name
  • age
  • email address
  • password
  • 姓名
  • 年龄
  • 电子邮件地址
  • 密码

Clicking on the radio button toggles the visibility of the Login/Signup fields:

单击单选按钮可切换登录/注册字段的可见性:

<form id="myForm">
    <input name="userAction" type="radio" value="login" checked="checked">Login</input>
    <br />
    <input name="userAction" type="radio" value="signup">Sign Up</input>

    <div id="loginFields" style="display:none">
        <!-- Login fields (email address and password) -->
    </div>

    <div id="signupFields" style="display:none">
        <!-- Signup fields (name, age, email address, password) -->
    </div>
</form>

I'm using the jQuery Validation plug-in, and I'd like to use the following rules:

我正在使用jQuery 验证插件,我想使用以下规则:

var signupRules = {
    emailAddressTextBox:
    {
        required: true,
        email: true 
    },
    passwordTextBox:
    {
        required: true,
        minlength: 6,
        maxlength: 24,
        passwordValidationRule: true // custom regex added with $.validator.addMethod()
    }
};

var loginRules = {
    nameTextBox:
    {
        required: true,
        maxlength: 50
    },
    loginEmailAddressTextBox:
    {
        required: true,
        email: true 
    },
    loginPasswordTextBox:
    {
        required: true,
        minlength: 6,
        maxlength: 24,
        passwordValidationRule: true // custom regex added with $.validator.addMethod()
    },
    loginPasswordAgainTextBox:
    {
        required: true,
        minlength: 6,
        maxlength: 24,
        equalTo: "#loginPasswordTextBox"
        passwordValidationRule: true // custom regex added with $.validator.addMethod()        
    }
};

How can I add the correct validation rule dynamically based on:

如何根据以下内容动态添加正确的验证规则:

   $("input[name='userAction']").change(function() {
        if ($("input[name='userAction']:checked" ).val() === "login") {
            // use loginRules
        } else {
            // use signupRules
        }
    });

I've tried the following:

我尝试了以下方法:

$("#myForm").validate({
    rules: ($("input[name='userAction']:checked" ).val() === "login") ? loginRules : signupRules;
});

But since my Login fields are the default displayed, its validations work, but the Signup scenario doesn't; it wants to validate Login fields for some reason. Am I missing something?

但是由于我的登录字段是默认显示的,它的验证工作,但注册场景没有;由于某种原因,它想验证登录字段。我错过了什么吗?

回答by Ryley

Ahh validation plugin, always so tricky :(

啊验证插件,总是那么棘手:(

First, I added id attributes to all the input boxes. Then, I made a change function for you:

首先,我为所有输入框添加了 id 属性。然后,我为你做了一个更改功能:

$("input[name='userAction']").change(function() {
    $('#signupFields').toggle();
    $('#loginFields').toggle();    
    if ($("input[name='userAction']:checked").val() === "login") {
        removeRules(signupRules);
        addRules(loginRules);
    } else {        
        removeRules(loginRules);
        addRules(signupRules);

    }
});

The add and remove functions look like this:

添加和删​​除功能如下所示:

function addRules(rulesObj){
    for (var item in rulesObj){
       $('#'+item).rules('add',rulesObj[item]);  
    } 
}

function removeRules(rulesObj){
    for (var item in rulesObj){
       $('#'+item).rules('remove');  
    } 
}

That's pretty much it. See here for a working example: http://jsfiddle.net/ryleyb/wHpus/66/

差不多就是这样。请参见此处的工作示例:http: //jsfiddle.net/ryleyb/wHpus/66/

EDIT: To me, the non-intuitive part is that I don't see an easy way to add/remove rules to the whole formafter you call validate, instead you have to manipulate the individual form elements.

编辑:对我来说,不直观的部分是我没有看到在调用后向整个表单添加/删除规则的简单方法validate,而是您必须操作单个表单元素。

回答by robert

Or you can use the dependsproperty.

或者您可以使用depends属性。

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

http://jqueryvalidation.org/category/plugin/搜索依赖

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")
        }
      }
    }
  }
});

回答by Boban Stojanovski

If you want to call validate again with new settings (rules,messages ... etc.) call

如果您想使用新设置(规则、消息...等)再次调用验证,请调用

$('#formid').removeData('validator')

This will remove validation for the form then initialize it again with the new settings

这将删除表单的验证,然后使用新设置再次初始化它

回答by FlavioEscobar

This post is from years ago, but since it has been viewed a lot of times, I think it would be useful to say that the jQuery Validation plugin now allows us to read, add and remove rules.

这篇文章是多年前的,但由于它已经被查看了很多次,我认为说 jQuery 验证插件现在允许我们读取、添加和删除规则会很有用。

Some examples:

一些例子:

  1. Print all rules attached to #myField: console.log($('#myField').rules());

  2. Remove an unwanted rule: $('#myField').rules('remove', 'min');

  3. Add a new rule: $('myField').rules('add', {min: 10});

  1. 打印附加到的所有规则#myFieldconsole.log($('#myField').rules());

  2. 删除不需要的规则: $('#myField').rules('remove', 'min');

  3. 添加新规则: $('myField').rules('add', {min: 10});

So say if you want to dynamically update the minimum value required. You can call a removeand a addright after:

所以说如果你想动态更新所需的最小值。您可以在以下时间调用 aremove和 a add

// Something happened. The minimum value should now be 100
$('#myField').rules('remove', 'min');
$('#myField').rules('add', {min: 100});

More information can be found here: https://jqueryvalidation.org/category/plugin/#-rules()

更多信息可以在这里找到:https: //jqueryvalidation.org/category/plugin/#-rules()

回答by wwanich

try this..

尝试这个..

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

credit from here.

信用从这里开始

回答by jeeber

There is an option now to ignore fields bases on selector criteria, such as invisible or disabled, such that you wouldn't have to change your rule set:

现在有一个选项可以根据选择器条件忽略字段,例如不可见或禁用,这样您就不必更改规则集:

.validate({
  ignore: ":not(:visible),:disabled",
  ...

回答by Dan

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

跟踪验证对象并直接删除/替换规则。使用 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;
}

回答by JPuchyr

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.

我有一个类似的问题,并通过向所有登录文本框添加“requiredForLogin”类和向所有注册文本框添加“requiredForSignUp”类来解决它。

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

然后使用 jQuery 的 toggleClass 和 jQuery.validate 的 addClassRules 根据按下的按钮打开和关闭规则。

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
        }
    });

});

回答by lboullo0

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:

看看我的回答https://stackoverflow.com/a/20547836/1399001。它包括一个有效的 jsfiddle。在您的示例中将是这样的:

$("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();

});

回答by Lingesh

the below code is working superb...

下面的代码工作得很好......

.validate({
  ignore: ":not(:visible),:disabled",
  ...