验证 onchange 输入字段 jQuery 验证插件
Validate onchange input fields jQuery Validate plugin
有一种情况,我们有一个下拉菜单可供选择值,还有 other
选项用于在文本输入字段中指定值。
只要选择,other
选项,显示一个文本字段,然后我希望将其验证。
select
是:
<select class="form-control" name="amount_sch" id="amount_sch">
<option value="" selected>Please Select</option>
<option value="1000">1000</option>
<option value="2000">2000</option>
<option value="othr_amt">Other, Please Specify</option>
</select>
input
是:
<input type="text" id="amount_sch_other" name="amount_sch_other"
class="form-control no-extras" placeholder="Enter Amount"
style="display:none;"/>
JQuery 到 show/hide:
$("#amount_sch").change(function() {
if ( $(this).val() == "othr_amt") {
$("#amount_sch_other").show();
}
else{
$("#amount_sch_other").hide();
}
});
rules
选项 .validate()
...
amount_sch : {
required : true,
}
有了这个,只有 select
被验证,但是当 text
字段可见时我如何验证它?
默认情况下,jQuery 验证插件将动态忽略任何隐藏字段的验证。所以你只需要为文本框声明验证规则,让插件自动完成它的事情。
rules: {
amount_sch: {
required: true,
},
amount_sch_other: {
required: true,
}
}
每当显示文本字段时,都会对其进行验证;当它被隐藏时,它不会被验证。
jQuery 验证插件默认忽略所有 hidden 元素。
对于你的情况,即使你像 Sparky 提到的那样将你的字段设置为必填。要么
只需添加 ignore: []
即可推送插件以验证表单中的所有隐藏元素。
$form.validate({
ignore: [],
...
有一种情况,我们有一个下拉菜单可供选择值,还有 other
选项用于在文本输入字段中指定值。
只要选择,other
选项,显示一个文本字段,然后我希望将其验证。
select
是:
<select class="form-control" name="amount_sch" id="amount_sch">
<option value="" selected>Please Select</option>
<option value="1000">1000</option>
<option value="2000">2000</option>
<option value="othr_amt">Other, Please Specify</option>
</select>
input
是:
<input type="text" id="amount_sch_other" name="amount_sch_other"
class="form-control no-extras" placeholder="Enter Amount"
style="display:none;"/>
JQuery 到 show/hide:
$("#amount_sch").change(function() {
if ( $(this).val() == "othr_amt") {
$("#amount_sch_other").show();
}
else{
$("#amount_sch_other").hide();
}
});
rules
选项 .validate()
...
amount_sch : {
required : true,
}
有了这个,只有 select
被验证,但是当 text
字段可见时我如何验证它?
默认情况下,jQuery 验证插件将动态忽略任何隐藏字段的验证。所以你只需要为文本框声明验证规则,让插件自动完成它的事情。
rules: {
amount_sch: {
required: true,
},
amount_sch_other: {
required: true,
}
}
每当显示文本字段时,都会对其进行验证;当它被隐藏时,它不会被验证。
jQuery 验证插件默认忽略所有 hidden 元素。
对于你的情况,即使你像 Sparky 提到的那样将你的字段设置为必填。要么
只需添加 ignore: []
即可推送插件以验证表单中的所有隐藏元素。
$form.validate({
ignore: [],
...