我在我的应用程序中有这个表单,我将通过AJAX提交它,但我想使用HTML5进行客户端验证。因此,我希望能够强制表单验证,也许通过jQuery。

我想在不提交表单的情况下触发验证。这可能吗?


当前回答

这使我能够显示带有表单验证的原生HTML 5错误消息。

<button id="btnRegister" class="btn btn-success btn btn-lg" type="submit"> Register </button>



$('#RegForm').on('submit', function () 
{

if (this.checkValidity() == false) 
{

 // if form is not valid show native error messages 

return false;

}
else
{

 // if form is valid , show please wait message and disable the button

 $("#btnRegister").html("<i class='fa fa-spinner fa-spin'></i> Please Wait...");

 $(this).find(':submit').attr('disabled', 'disabled');

}


});

注意:RegForm是表单id。

参考

希望能帮助别人。

其他回答

var $myForm = $('#myForm ');
if (!$myForm[0].checkValidity()) {
  $('<input type="submit">').hide().appendTo($myForm).click().remove();
}
$(document).on("submit", false);

submitButton.click(function(e) {
    if (form.checkValidity()) {
        form.submit();
    }
});

2022香草JS解决方案

纯JavaScript提供了所需的所有函数。我知道这个问题是关于jQuery的,但即使是jQuery的答案也使用了这些函数,即checkValidity()和reportValidity()。

测试整个表单

let form = document.getElementById('formId');
// Eventlistener can be another event and on another DOM object this is just an example
form.addEventListener('submit', function (event) {
    // Only needed if event is submit, otherwise this line can be skipped 
    event.preventDefault();

    // This is the important part, test if form is valid
    if (form.checkValidity() === false){
        // This is the magic function that displays the validation errors to the user
        form.reportValidity();   
        return; 
    }

    // Code if all fields are valid; continue form submit or make Ajax call.
})

测试特定领域

checkValidity()和reportValidity()不仅可以在表单上使用,还可以在特定的字段上使用。如果不需要,不需要创建表单或虚拟提交按钮。

// Get field of interest
let inputElement = document.querySelector("[name='" + inputName + "']");
// Check if the element is valid
if (inputElement.checkValidity() === false){
    // If not, show the errors to the user
    inputElement.reportValidity();
    return;
}

// Nothing? Great, continue to the Ajax call or whatever

显然,这必须在由事件侦听器调用的函数中才有意义。

根据这个问题,html5的有效性首先应该使用jQuery进行验证,在大多数答案中,这是不会发生的,原因如下:

同时使用html5表单的默认函数进行验证

checkValidity();// returns true/false

我们需要理解jQuery返回对象数组,而选择像这样

$("#myForm")

因此,您需要指定第一个索引以使checkValidity()函数工作

$('#myForm')[0].checkValidity()

以下是完整的解决方案:

<button type="button" name="button" onclick="saveData()">Save</button>

function saveData()
{
    if($('#myForm')[0].checkValidity()){
        $.ajax({
          type: "POST",
          url: "save.php",
          data: data,
          success: function(resp){console.log("Response: "+resp);}
        });
    }
}

要检查某个字段是否有效,请使用:

$('#myField')[0].checkValidity(); // returns true|false

要检查表单是否有效,请使用:

$('#myForm')[0].checkValidity(); // returns true|false

如果你想显示某些浏览器(如Chrome)的原生错误消息,不幸的是,唯一的方法是通过提交表单,就像这样:

var $myForm = $('#myForm');

if (!$myForm[0].checkValidity()) {
    // If the form is invalid, submit it. The form won't actually submit;
    // this will just cause the browser to display the native HTML5 error messages.
    $myForm.find(':submit').click();
}

请记住,到目前为止,并不是所有浏览器都支持HTML5验证。