点击按钮手动触发HTML验证

17

我试图在按钮点击时处理表单验证。它正在验证表单,但没有显示错误。

有人能帮帮我吗?

<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/

5个回答

35

尝试

reportValidity()

那么你就会拥有

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

4
完美!https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLFormElement/reportValidity - WayFarer

6
我通过以下步骤实现了这个:
1)我有一个表单:
<form>
    <textarea required></textarea>
    <input type="submit" style="display:none;"/>
</form>

<a>Some other button to trigger event</a>

现在我们需要检查表格是否填写正确:
//this is <a> click event:
if (!$('form')[0].checkValidity()) {
    $('form').find('input[type="submit"]').click();
    return false;
}

这将触发表单发送,但由于存在错误而不会发送 ;)
看起来在点击input[type="submit"]时显示html5验证错误 :)
希望对您也有用! :)

我更喜欢使用您的策略,但也创建一个提交钩子来执行实际的提交工作。调用event.preventDefault()会阻止浏览器执行表单操作。因此,<a>点击事件将简单地是$('form').find('input[type="submit"]').click()$('form').on("submit", function(event) { event.preventDefault(); /* 在这里编写您的代码 */}) - Roger Kaplan

4

这里是完美的答案。

<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;
}

});


0

移除 else 语句。(更新)

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

我不想在警告框中显示错误,而应该在 Bootstrap 弹出框中显示错误,这是 HTML5 的默认行为。 - Imran Rashid
@ImranRashid 我明白了。移除 'else' 语句:{ //显示错误 alert('未验证'); } - Elmer
请检查 http://jsfiddle.net/5ycZz/,如果我将按钮类型更改为“submit”,它就可以工作,否则它不会显示任何消息。 - Imran Rashid
@ImranRashid 你给我的小提琴中的按钮类型为"type=button",它可以工作,并显示验证框。 - Elmer

-1

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接