jquery 验证添加动态所需的输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19340021/
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 23:43:11  来源:igfitidea点击:

jquery validation add inputs required dynamically

jquerydynamicjquery-validate

提问by Andres

I am currently using the bassistance jquery validationor the jqueryvalidation plugin(they renamed it) and I have it validating a form like so:

我目前正在使用bassistance jquery 验证或 jqueryvalidation 插件(他们重命名了它),并且我让它验证了一个像这样的表单:

if($.fn.validate) {
        $("#frmNewOrder").validate({
            rules: {
                txtAmount: {
                    required: true,
                    digits: true
                },
                ddlAccount: {
                    required: true
                },
                ddlBank: {
                    required: true
                }
            }
        });
    }

Now depending on the amount I need to require or not an extra field a dropdownlist and depending on that dropdownlist another text input. so it's like:

现在取决于我需要或不需要额外字段下拉列表的数量,并根据该下拉列表另一个文本输入。所以它就像:

 if($('#txtAmount').val() >= 10000){
     //add ddlReason required
 }

 if($('#ddlReason').val() == 'o'){
     //add txtReason required
 }

I've tried adding the css class 'required' like the other fields but I take it if they are not inside the rules then it doesn't work? I've tried adding rules like this:

我试过像其他字段一样添加 css 类“必需”,但如果它们不在规则内,我就接受它,然后它不起作用?我试过添加这样的规则:

 $( "#ddlReason" ).rules( "add", {
        required: true});

and that doesn't work either. any suggestions?

这也不起作用。有什么建议?

EDIT: Here's the linkto the jquery validate that I'm using. if I used rules outside it gives this error:

编辑:这是我正在使用的 jquery 验证的链接。如果我在外部使用规则,则会出现此错误:

Uncaught TypeError: Cannot read property 'settings' of undefined 

on line 124:

在第 124 行:

var settings = $.data(element.form, 'validator').settings;

and using the suggestions I've seen in other places i've done this which is what causes the error:

并使用我在其他地方看到的建议,我已经这样做了,这就是导致错误的原因:

var defaultrules = {
    txtAmount: {
        required: true,
        digits: true
    }
}

if($.fn.validate) {
    $("#frmNewOrder").validate();
    addRules(defaultrules);
}

EDIT 2: here's the html markup, hope it helps.

编辑 2:这是 html 标记,希望它有所帮助。

<form id="frmNewOrder" name="frmNewOrder" action="" method="post">
<label>Amount</label>
<input type="text" name="txtAmount" id="txtAmount" class="required" />
<button id="calculate" type="button">Calculate</button>
<div id="dvreason" style="display:none;">
    <select id="ddlReason" name="ddlReason">
         <option></option>
         <option value="i">Option 1</option>
         <option value="o">Other</option>
    </select>
    <div id="dvother" style="display:none">
       <label>Other reason</label>
       <input type="text" name="txtOther" id="txtOther" />
    </div>
</div>
<input type="submit" name="send" id="send" value="Send" />
</form>

采纳答案by nsawaya

faced similar issue with it,

遇到了类似的问题,

in fact what you'll notice is that validator is undefined at line 124, i.e. there is no validator instance associated with the form

事实上,您会注意到验证器在第 124 行未定义,即没有与表单关联的验证器实例

if you check the validate method you see that if validator is undefined it will create a new one

如果您检查验证方法,您会看到如果验证器未定义,它将创建一个新的

var validator = $.data(this[0], 'validator');
        if ( validator ) {
            return validator;
        }

        // Add novalidate tag if HTML5.
        this.attr('novalidate', 'novalidate');

            //HERE it is creating a new one using the constructor   
        validator = new $.validator( options, this[0] );
        $.data(this[0], 'validator', validator);

Apparently the rulesmethod assumes that validator is already there in the form object, so from my understanding, and since validatereturns validator instance, you can call validateand then append your extra rules to the returned validator settings.rulesobject and re-run again which is not very practical.

显然该rules方法假设验证器已经存在于表单对象中,所以根据我的理解,并且由于validate返回验证器实例,您可以调用validate然后将额外的规则附加到返回的验证器settings.rules对象并再次重新运行,这不是很实用。

The other solution would be to simply append the added rules to the initial rules object before calling validate

另一种解决方案是在调用之前简单地将添加的规则附加到初始规则对象 validate

So in my case I wanted the input field to be validated as number however I didn't want Google Chrome to make it a number field (just try in Chrome to see what I mean, this had the issue of bypassing the type number validation in case the user entered manually, and in my case the user will most probably enter the number manually)

因此,在我的情况下,我希望将输入字段验证为数字,但是我不希望 Google Chrome 将其设为数字​​字段(只需在 Chrome 中尝试看看我的意思,这存在绕过类型号验证的问题)如果用户手动输入,而在我的情况下,用户很可能会手动输入号码)

code example:

代码示例:

var customRule = {number: true};

//suppose populateValidateRules() fills your initial rules, which is my case at least
var validationRules =  populateValidateRules();

validationRules["rules"].fieldToBeDynamicallyModifiedForValidation= customRule;

$(formId).validate(validationRules);

Hope this helps

希望这可以帮助

回答by pikachu0

I'd gotten the same error message as well and realised that I should call the validate()on the form first before I call rules()on individual input fields. This behaviour is documented.

我也收到了相同的错误消息,并意识到我应该validate()在调用rules()单个输入字段之前先调用表单上的 。此行为已记录在案

$('#form').validate({
  rules: {
    email: {
      email: true
    }
  }
});

$('#email').rules('add', {
  required: true
});

This may not be the answer to OP's problem, but I'm posting this to help anyone who searched jquery validation Cannot read property settings of undefinedand clicked this page.

这可能不是 OP 问题的答案,但我发布此信息是为了帮助搜索jquery validation Cannot read property settings of undefined并单击此页面的任何人。

Thanks to the hint given by @nsawaya!

感谢@nsawaya给出的提示!

回答by George SEDRA

their is a problem while getting the dynamic add element using the id so it is working if you use attribute selector so for example add attribute data="ddlReason"and make it like this :

他们在使用 id 获取动态添加元素时会出现问题,因此如果您使用属性选择器,则它可以正常工作,例如添加属性data="ddlReason"并使其像这样:

$( "input[data='ddlReason']" ).rules( "add", {
        required: true
});