javascript 单击按钮时手动触发HTML验证

yh2wf1be  于 2023-02-18  发布在  Java
关注(0)|答案(5)|浏览(98)

我正在尝试处理按钮点击时的表单验证。它正在验证表单,但没有显示错误。
有人能帮我一下吗?

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

ffscu2ro

ffscu2ro1#

试试看

reportValidity()

所以你得

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

xggvc2p62#

我通过以下步骤实现了这一点:
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;
}

将触发表单发送,但由于存在错误而不会发送;)

输入[type=“submit”]时显示html5验证错误,单击:)

希望也会为你工作!:)

5jvtdoz2

5jvtdoz23#

这就是完美的答案

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

});

vptzau2j

vptzau2j4#

删除else语句。(更新)

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

t3irkdon5#

您应该能够简单地添加onclick=“return validateForm()"。

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

相关问题