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

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


当前回答

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

问题是,当你的<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验证(类型和模式匹配),而无需提交表单。

其他回答

我找到了一个适合我的方法。 只需要像这样调用一个javascript函数:

action=“javascript:myFunction();”

然后是html5验证……真的很简单:-)

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

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

$(document).on("submit", false);

submitButton.click(function(e) {
    if (form.checkValidity()) {
        form.submit();
    }
});
$("#form").submit(function() { $("#saveButton").attr("disabled", true); });

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

这种方法对我来说很有效:

Add onSubmit attribute in your form, don't forget to include return in the value. <form id='frm-contact' method='POST' action='' onSubmit="return contact()"> Define the function. function contact(params) { $.ajax({ url: 'sendmail.php', type: "POST", dataType: "json", timeout: 5000, data: { params:params }, success: function (data, textStatus, jqXHR) { // callback }, error: function(jqXHR, textStatus, errorThrown) { console.log(jqXHR.responseText); } }); return false; }