ajax提交前的HTML5验证 [英] HTML5 validation before ajax submit

查看:36
本文介绍了ajax提交前的HTML5验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

形式:

<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@example.com" />
  <label for="message">Message:</label>
  <textarea name="message" id="message" required></textarea>
  <input type="submit" id="submit"/>
</form>

提交:

$('#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");
        }
    });
});

推荐答案

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

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

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

这篇关于ajax提交前的HTML5验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆