【问题标题】:Manually trigger html5 validation on button click单击按钮时手动触发 html5 验证
【发布时间】:2019-11-14 14:11:09
【问题描述】:

我正在尝试处理按钮单击时的表单验证。它正在验证表单但未显示错误。 有人可以帮我吗?

<form id="the-form" action="#">
    <input type="text" required="required" placeholder="Required text" />
    <input type="email" required="required" placeholder="email" />
    <button id="btn" type="button">Submit</button>
</form>

javascript:

$("#btn").on("click", function(){
    if($("#the-form")[0].checkValidity())
    {
        alert('validated');
    }
    else
    {
        //show errors
        return false;
    }
});

http://jsfiddle.net/5ycZz/

【问题讨论】:

    标签: html5-validation


    【解决方案1】:

    试试

    reportValidity()
    

    所以你有

    $("#btn").on("click", function(){
        if($("#the-form")[0].checkValidity()) {
            alert('validated');
        }
        else {
            $("#the-form")[0].reportValidity();
        }
    });
    

    【讨论】:

    【解决方案2】:

    我通过以下步骤实现了这一点:

    1) 我有表格:

    <form>
        <textarea required></textarea>
        <input type="submit" style="display:none;"/>
    </form>
    
    <a>Some other button to trigger event</a>
    

    2) 现在我们要检查表格是否填写正确:

    //this is <a> click event:
    if (!$('form')[0].checkValidity()) {
        $('form').find('input[type="submit"]').click();
        return false;
    }
    

    这将触发表单发送但不会发送,因为有错误;)

    在 input[type="submit"] click 上似乎显示 html5 验证错误:)

    希望对你也有用! :)

    【讨论】:

    【解决方案3】:

    这里是完美的答案

    <form id="the-form" action="#">
    <input type="text" required="required" placeholder="Required text" />
    <input type="email" required="required" placeholder="email" />
    <button id="btn" type="submit">Submit</button>
    

    $("#btn").on("click", function(){
    if($("#the-form")[0].checkValidity())
    {
        alert('validated');
    }
    else
    {
      return 0;
    }
    

    });

    【讨论】:

      【解决方案4】:

      删除 else 语句。 (更新)

      $("#btn").on("click", function(){
      if($("#the-form")[0].checkValidity())
      {
          alert('validated'); //will appear if name and email are of valid formats
      }
      });
      

      【讨论】:

      • 我不想在警报中显示错误,它应该在引导弹出窗口中显示错误,这是 html5 的默认行为
      • @ImranRashid 我明白了。删除 'else' 语句: else { //显示错误 alert('notvalidated'); }
      • 检查jsfiddle.net/5ycZz..如果我更改按钮类型以提交它可以正常工作,否则它不会显示任何消息
      • @ImranRashid 你给我的小提琴有按钮 type="button" 可以工作。它显示了验证框。
      【解决方案5】:

      您应该可以简单地添加 onclick="return validateForm()"。

      <button id="btn" onclick="return validateForm()" type="button">Submit</button>
      

      【讨论】:

        猜你喜欢
        • 2012-09-12
        • 2017-06-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-10
        • 1970-01-01
        • 2017-05-31
        相关资源
        最近更新 更多