[英]Using JQuery how do I check two fields that I need one filled only
Using jQuery my user only has to enter one field, ssn or phone but how do I check in the jquery validate that one is check? 使用jQuery,我的用户只需要输入一个字段,ssn或phone,但是如何在jquery中进行校验以确认一个是check?
<script type="text/javascript">
$(document).ready(function () {
$("#memberrequest").validate({
rules: {
phonenumber: {
minlength: 12,
maxlength: 12
},
ssn: {
minlength: 10,
maxlength: 10
}
}
});
});
</script>
Please help me out 请帮帮我
I made a fiddle for you based on what you posted, it would still have to be customized but it demonstrates what you are asking. 我根据您发布的内容为您做了一个小提琴,它仍然必须进行自定义,但它可以说明您的要求。
http://jsfiddle.net/whytheday/QP4wd/1/ http://jsfiddle.net/whytheday/QP4wd/1/
$(document).ready(function () {
$("#memberrequest").validate({
rules: {
phonenumber: {
minlength: 12,
maxlength: 12,
required: {
depends: function(element){
return $("#ssn").val().trim() == ""
}
}
},
ssn: {
minlength: 10,
maxlength: 10,
required: {
depends: function(element){
return $("#phonenumber").val().trim() == ""
}
}
}
}
});
});
You just set it to required and then you can set a dependency and you can check if the other field has a value. 您只需将其设置为必填,然后可以设置依赖项,然后可以检查其他字段是否具有值。
Take a look at the options for "required" http://docs.jquery.com/Plugins/Validation/Methods/required#dependency-expression . 查看“必需”的选项http://docs.jquery.com/Plugins/Validation/Methods/required#dependency-expression 。 You can specify a dependency expression or a dependency callback. 您可以指定依赖项表达式或依赖项回调。 This means you are providing a bit of javascript code (within the class attribute, where the example just says required:true), and you're saying "if my bit of code evaluates as true, then this form element is required". 这意味着您要提供一些javascript代码(在class属性中,示例仅说明了required:true),并且您说的是“如果我的代码评估为true,那么此form元素是必需的”。
So in your case, both the phone number and the ssn fields would need dependency expressions that say "if the other one is empty, this one is required". 因此,在您的情况下,电话号码和ssn字段都需要依赖项表达式,例如“如果另一个为空,则需要此”。
You could loop over both fields, and see if either has a value: 您可以遍历两个字段,然后查看其中一个是否具有值:
$( function () {
var passesValidation = false;
$('input').each( function() {
if ( $(this).val() ) { passesValidation = true; } // could add optional check against length for this field
// $(this).val().length && $(this).val().length >= $(this).attr('data-minlength') or some such
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.