相关字段的jQuery验证

时间:2016-04-28 12:46:22

标签: jquery jquery-validate

我正在尝试验证具有以下结构的表单:

<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插件实现它。

1 个答案:

答案 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>