Manually trigger html5 validation on button click

一世执手 提交于 2019-12-22 03:54:23

问题


I am trying to handle form validation on button click. It is validating the form but not showing error. can anyone help me in this?

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


回答1:


I've achieved this by doing steps below:

1) I'm having form:

<form>
    <textarea required></textarea>
    <input type="submit" style="display:none;"/>
</form>

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

2) Now we have to check if the form is filled correctly:

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

This will trigger form sending but won't send because there are errors ;)

It appears that html5 validation errors are displayed on input[type="submit"] click :)

Hope will work for You too! :)




回答2:


Try

reportValidity()

So you'd have

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



回答3:


here is the perfect answer

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


Remove the else statement. (Update)

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



回答5:


You should be able to simply add onclick="return validateForm()".

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


来源:https://stackoverflow.com/questions/18634106/manually-trigger-html5-validation-on-button-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!