我正在尝试验证具有以下结构的表单:
<form id="myform" action="#" method="post">
<fieldset>
<legend>Form 1</legend>
<label for="field1">Certificate Number</label>
<input id="field1" type="text" class="myClass1" name="field1" placeholder="field1">
</fieldset>
<fieldset>
<legend>Form 2</legend>
<label for="field2">Certificate Number</label>
<input id="field2" type="text" class="myClass2" name="field2" placeholder="field2">
<br>
<label for="field3">Redemption Code</label>
<input id="field3" type="text" class="myClass2" name="field3" placeholder="field3">
</fieldset>
<input type="submit" value="Continue">
</form>
我想验证以下条件:
(field1 || (field2 && field3))
这非常简单,但我不确定如何使用jQuery Validate插件实现它。
答案 0 :(得分:2)
可能有办法使用require_from_group
。
虽然您可以将required
用作以下功能: -
$('#myform').validate({
rules: {
field1:{
required:function (){ return !$('#field2').val().length && !$('#field3').val().length; }
},
field2:{
required:function (){ return !$('#field1').val().length }
},
field3:{
required:function (){ return !$('#field1').val().length }
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.0/jquery.validate.min.js"></script>
<form id="myform" action="#" method="post">
<fieldset>
<legend>Form 1</legend>
<label for="field1">Certificate Number</label>
<input id="field1" type="text" class="myClass1" name="field1" placeholder="field1">
</fieldset>
<fieldset>
<legend>Form 2</legend>
<label for="field2">Certificate Number</label>
<input id="field2" type="text" class="myClass2" name="field2" placeholder="field2">
<br>
<label for="field3">Redemption Code</label>
<input id="field3" type="text" class="myClass2" name="field3" placeholder="field3">
</fieldset>
<input type="submit" value="Continue">
</form>