【问题标题】:HTML5 required attribute one of two fieldsHTML5 必需的两个字段之一的属性
【发布时间】:2014-08-15 17:31:15
【问题描述】:

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

<form>
    <input type="tel" name="telephone" required>
    <input type="tel" name="mobile" required>
    <input type="submit" value="Submit">
</form>

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

【问题讨论】:

  • 我认为这将超出 HTML 的控制范围,您必须实现某种 JS 功能。一个快速的谷歌显示这个 jsfiddle jsfiddle.net/LEZ4r/1 所以你可以有一个 if 语句来控制。希望这会有所帮助...
  • 查看this答案!

标签: html forms validation


【解决方案1】:

无论如何,您最好使用 Javascript 进行表单数据验证,因为 HTML5 验证在旧浏览器中不起作用。方法如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Form Validation Phone Number</title>
</head>
<body>
    <form name="myForm" action="data_handler.php">
        <input type="tel" name="telephone">
        <input type="tel" name="mobile">
        <input type="button" value="Submit" onclick="validateAndSend()">
    </form>
    <script>
        function validateAndSend() {
            if (myForm.telephone.value == '' && myForm.mobile.value == '') {
                alert('You have to enter at least one phone number.');
                return false;
            }
            else {
                myForm.submit();
            }
        }
    </script>
</body>
</html>

.
现场演示:http://codepen.io/anon/pen/LCpue?editors=100。如果您愿意,请告诉我这是否适合您。

【讨论】:

  • 感谢您的回答。但是,表单验证是在服务器端完成的,所以我不会为旧浏览器而烦恼。 HTML5 表单验证是对使用较新浏览器的用户的渐进增强,我想使用它并显示浏览器的本机错误消息
  • @Andy -- 嗯?但你自己的答案也是 Javascript?
  • 我的答案只是编辑输入的required 属性,以利用现代浏览器的HTML5 表单验证。您的答案实现了自定义客户端验证。
【解决方案2】:

更新 2020-06-21 (ES6):

鉴于 jQuery 在 JavaScript 世界中变得有些过时,并且 ES6 提供了一些不错的语法糖,我编写了一个与原始答案等效的纯 JS:

document.addEventListener('DOMContentLoaded', function() {
  const inputs = Array.from(
    document.querySelectorAll('input[name=telephone], input[name=mobile]')
  );

  const inputListener = e => {
    inputs
      .filter(i => i !== e.target)
      .forEach(i => (i.required = !e.target.value.length));
  };

  inputs.forEach(i => i.addEventListener('input', inputListener));
});
<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>

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

原始答案 (jQuery):

我尝试了一些想法,现在使用 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);
    });
});

我写了一个 jQuery plugin 包装了上面的 JavaScript 代码,以便它可以用于多组元素。

【讨论】:

  • 你的脚本比我的有什么优势,哪个更简单(在你写这个答案之前你把它弄红了)?
  • 正如您在回复中提到的,这种方法的好处是它使用了浏览器的原生表单验证,而不是自定义客户端验证。
【解决方案3】:

对于两个文本字段,@Andy 的回答非常棒,但是如果有两个以上的字段,我们可以使用这样的东西。

jQuery(function ($) {
    var $inputs = $('input[name=phone],input[name=mobile],input[name=email]');
    $inputs.on('input', function () {
        var total = $('input[name=phone]').val().length + $('input[name=mobile]').val().length + $('input[name=email]').val().length;
        $inputs.not(this).prop('required', !total);

    });
});

【讨论】:

  • 我的答案适用于任意数量的字段 :) 这是一个使用三个字段的演示:jsfiddle.net/v17wycn0
  • 你正在写它的工作。但是试试这个场景。填写电话字段,而不是填写手机字段,现在擦除其中一个,您已经擦除了一个字段,但仍然填写了一个字段。但尝试提交。它不允许您这样做,因为其余两个字段都是必需的。其余两份,一份填写,一份未填写,所以表单不会提交。
  • 但是非常感谢,我在一天内第二次使用您的解决方案 :) 干杯...
  • 我试过你的方案,你是对的!干得好:) 我需要在我的插件中解决这个问题
【解决方案4】:

根据安迪的回答,但我需要一个复选框实现并想出了这个。

what role(s) do you want?
<input type="checkbox" data-manyselect="roler" name="author" required>
<input type="checkbox" data-manyselect="roler" name="coder" required>
<input type="checkbox" data-manyselect="roler" name="teacher" required>

where will you work?
<input type="checkbox" data-manyselect="placement" name="library" required>
<input type="checkbox" data-manyselect="placement" name="home" required>
<input type="checkbox" data-manyselect="placement" name="office" required>
jQuery(function ($) {
    // get anything with the data-manyselect
    // you don't even have to name your group if only one group
    var $group = $("[data-manyselect]");

    $group.on('input', function () {
        var group = $(this).data('manyselect');
        // set required property of other inputs in group to false
        var allInGroup = $('*[data-manyselect="'+group+'"]');
        // Set the required property of the other input to false if this input is not empty.
        var oneSet = true;
        $(allInGroup).each(function(){
            if ($(this).prop('checked'))
                oneSet = false;
        });
        $(allInGroup).prop('required', oneSet)
    });
});

其他任何人都可以通过谷歌搜索并希望快速解决许多复选框中的一个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    • 2012-06-06
    • 1970-01-01
    • 2019-04-28
    相关资源
    最近更新 更多