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

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


当前回答

在不使用提交按钮的情况下检查所有必须填写的字段,您可以使用下面的功能。

您必须为控件分配所需的属性。

  $("#btnSave").click(function () {
    $(":input[required]").each(function () {                     
        var myForm = $('#form1');
        if (!$myForm[0].checkValidity()) 
          {                
            $(myForm).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

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

$("#form").submit(function() { $("#saveButton").attr("disabled", true); });

不是最好的答案,但对我来说是可行的。

你可以在不提交表单的情况下完成。

例如,如果id为“search”的表单提交按钮是另一种表单。你可以在提交按钮上调用click event,然后调用ev。然后是preventDefault。 对于我的案例,我验证表单A提交的表单B。 像这样

function validateFormB(ev){ // DOM Event object
  //search is in Form A
  $("#search").click();
  ev.preventDefault();
  //Form B validation from here on
}

下面的代码为我工作,

$("#btn").click(function () {

    if ($("#frm")[0].checkValidity())
        alert('sucess');
    else
        //Validate Form
        $("#frm")[0].reportValidity()

});

也许是迟到了,但不知何故,我在试图解决类似的问题时发现了这个问题。由于该页没有代码为我工作,同时我提出了解决方案,工作如指定。

问题是,当你的<form> DOM包含单个<button>元素时,一旦触发,<button>将自动sumbit形式。如果您使用AJAX,您可能需要防止默认操作。但有一个问题:如果你只是这样做,你也会阻止基本的HTML5验证。因此,只有当表单有效时,才应该防止该按钮的默认值。否则,HTML5验证将阻止你提交。jQuery checkValidity()将帮助这:

jQuery:

$(document).ready(function() {
  $('#buttonID').on('click', function(event) {
    var isvalidate = $("#formID")[0].checkValidity();
    if (isvalidate) {
      event.preventDefault();
      // HERE YOU CAN PUT YOUR AJAX CALL
    }
  });
});

上面描述的代码将允许您使用基本的HTML5验证(类型和模式匹配),而无需提交表单。