HTML5必需属性是两个字段之一

And*_*ndy 22 forms validation html5

我有一个包含两个必填输入字段的表单:

<form>
    <input type="tel" name="telephone" required>
    <input type="tel" name="mobile" required>
    <input type="submit" value="Submit">
</form>
Run Code Online (Sandbox Code Playgroud)

是否可以让浏览器进行验证,因此只需要其中一个?即如果电话被填满,请不要抛出关于移动电话为空的错误,反之亦然

And*_*ndy 36

我玩了一些想法,现在有一个使用jQuery解决这个问题的工作方案:

jQuery(function ($) {
    var $inputs = $('input[name=telephone],input[name=mobile]');
    $inputs.on('input', function () {
        // Set the required property of the other input to false if this input is not empty.
        $inputs.not(this).prop('required', !$(this).val().length);
    });
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
  Telephone:
  <input type="tel" name="telephone" value="" required>
  <br>Mobile:
  <input type="tel" name="mobile" value="" required>
  <br>
  <input type="submit" value="Submit">
</form>
Run Code Online (Sandbox Code Playgroud)

input在两个输入上使用事件,当一个不为空时,它将另一个输入的必需属性设置为false.

我编写了一个包含上述JavaScript代码的jQuery插件,以便可以在多组元素上使用它.

  • 正如对您的答案的回复中提到的,这种方法的好处是它使用浏览器的本机表单验证而不是自定义客户端验证。 (3认同)