jQuery ajax提交前的HTML5验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15713491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:39:03  来源:igfitidea点击:

HTML5 validation before ajax submit

jqueryajaxhtmlformsvalidation

提问by Sorry-Im-a-N00b

This should be simple, yet it's driving me crazy. I have an html5 form that I am submitting with ajax. If you enter an invalid value, there is a popup response that tells you so. How can I check that the entries are valid before I run my ajax submit?

这应该很简单,但它让我发疯。我有一个 html5 表单,我用 ajax 提交。如果您输入了无效值,则会有一个弹出式响应告诉您。在运行 ajax 提交之前,如何检查条目是否有效?

form:

形式:

<form id="contactForm" onsubmit="return false;">
  <label for="name">Name:</label>
  <input type="text" name="name" id="name" required placeholder="Name" />
  <label for="subject">Subject:</label>
  <input type="text" name="subject" id="subject" required placeholder="Subject" />
  <label for="email">Email:</label>
  <input type="email" name="email" id="email" required placeholder="[email protected]" />
  <label for="message">Message:</label>
  <textarea name="message" id="message" required></textarea>
  <input type="submit" id="submit"/>
</form>

submit:

提交:

$('#submit').click(function(){
    var name = $("input#name").val();
    var subject = $("input#subject").val();
    var email = $("input#email").val();
    var message = $("input#message").val();

    var dataString = 'email=' + email + '&message=' + message + '&subject=' + subject + '&name=' + name ; 

    $.ajax({
        url: "scripts/mail.php",
        type:   'POST',
        data: dataString,
        success: function(msg){
            disablePopupContact();
            $("#popupMessageSent").css("visibility", "visible");
        },
        error: function() {
            alert("Bad submit");
        }
    });
});

回答by antinescience

By default, jQuery doesn't know anything about the HTML5 validation, so you'd have to do something like:

默认情况下,jQuery 对 HTML5 验证一无所知,因此您必须执行以下操作:

$('#submit').click(function(){
    if($("form")[0].checkValidity()) {
        //your form execution code
    }else console.log("invalid form");
});

回答by csbarnes

If you bind to the submit event instead of click it will only fire if it passes the HTML5 validation.

如果您绑定到提交事件而不是单击它只会在它通过 HTML5 验证时触发。

It is best practice to cache your jQuery selectors in variables if you use it multiple times so you don't have to navigate the DOM each time you access an element. jQuery also provides a .serialize() function that will handle the form data parsing for you.

如果您多次使用 jQuery 选择器,最好将其缓存在变量中,这样您就不必每次访问元素时都导航 DOM。jQuery 还提供了一个 .serialize() 函数,它将为您处理表单数据解析。

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

$contactForm.on('submit', function(ev){
    ev.preventDefault();

    $.ajax({
        url: "scripts/mail.php",
        type:   'POST',
        data: $contactForm.serialize(),
        success: function(msg){
            disablePopupContact();
            $("#popupMessageSent").css("visibility", "visible");
        },
        error: function() {
            alert("Bad submit");
        }
    });
});

回答by Musa

If you are using HTML5 form validation you'll have to send the ajax request in the form's submit handler. The submit handler will only trigger if the form validates. What you're using is a button click handler which will always trigger because it has no association with form validation. NOTE: not all browsers support html5 form validation.

如果您使用 HTML5 表单验证,则必须在表单的提交处理程序中发送 ajax 请求。提交处理程序只会在表单验证时触发。您使用的是一个按钮单击处理程序,它总是会触发,因为它与表单验证没有关联。注意:并非所有浏览器都支持 html5 表单验证。

回答by Mfoo

I prefer using the jQuery submit handler, you will still get the response to your form with the following method.

我更喜欢使用 jQuery 提交处理程序,您仍然可以使用以下方法获得对表单的响应。

jQuery('#contactForm').on('submit', function (e) {
    if (document.getElementById("contactForm").checkValidity()) {
        e.preventDefault();
        jQuery.ajax({
            url: '/some/url',
            method: 'POST',
            data: jQuery('#contactForm').serialize(),
            success: function (response) {
                //do stuff with response
            }
        })
    }
    return true;
});

回答by Kurt

Not exactly sure what you mean. But I assume that you want to check in realtime if the input is valid. If so you should use .keyup instead of .click event, because this would lead to an action if the user presses submit. Look at http://api.jquery.com/keyup/

不完全确定你的意思。但我假设您想实时检查输入是否有效。如果是这样,您应该使用 .keyup 而不是 .click 事件,因为如果用户按下提交,这将导致操作。查看http://api.jquery.com/keyup/

With this you could check the input with every new character insert and display e.g. "not valid" until your validation ist true.

有了这个,您可以检查每个新字符插入的输入并显示例如“无效”,直到您的验证为真。

I hope this answers your question!

我希望这回答了你的问题!

回答by Amol

U can also use jquery validate method to validate form like

你也可以使用 jquery 验证方法来验证表单

$("#form id").validate();

$("#form id").validate();

which return boolean value based on form validation & also u can see the error in log using errorList method.

它根据表单验证返回布尔值,您还可以使用 errorList 方法查看日志中的错误。

for use above functionality u must include jquery.validate.js file in your script

要使用上述功能,您必须在脚本中包含 jquery.validate.js 文件