简体   繁体   English

HTML5必需属性不适用于AJAX提交

[英]HTML5 required attribute not working with AJAX submission

I am trying to do some basic validation for a simple newsletter form I have that only requires an email. 我正在尝试对我只需要电子邮件的简单时事通讯表格进行一些基本验证。 The way I have this form/input within the page, there really isn't room to add any jQuery validate error messages, so I was trying to add a simple HTML 5 required attribute, but the form submits regardless if blank. 我在页面中有这个表单/输入的方式,实际上没有空间添加任何jQuery验证错误消息,所以我试图添加一个简单的HTML 5必需属性,但表单提交无论是否为空。

What would be the best way to add some simple validation to this so the form checks for an email address, it is filled in, and min length of 4 characters? 为此添加一些简单验证的最佳方法是什么,以便表单检查电子邮件地址,填写,最小长度为4个字符?

<form action="" method="POST" id="newsletter-form">
    <input type="email" id="footer-grid1-newsletter-input" placeholder="Your Email Address" required>
    <input type="submit" id="footer-grid1-newsletter-submit" name="submit" value='&nbsp'>
</form>
$("#footer-grid1-newsletter-submit").on("click", function (event) {
    event.preventDefault();
    var newsletter_email = $("#footer-grid1-newsletter-input").val();
    var targeted_popup_class = jQuery(this).attr('data-popup-open');
    $.ajax({ 
        url: "newsletterSend.php", 
        type: "POST",
        data: {
            "newsletter_email": newsletter_email
        },
        success: function (data) {
            //  console.log(data); // data object will return the response when status code is 200
            if (data == "Error!") {
                alert("Unable to insert email!");
                alert(data);
            } else {
                $("#newsletter-form")[0].reset();
                $('.newsletter-popup').fadeIn(350).delay(2000).fadeOut();
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            alert(textStatus + " | " + errorThrown);
            //console.log("error"); //otherwise error if status code is other than 200.
        }
    });
});

在此输入图像描述

The reason is because the validation is done on the submit event of the form, yet you have hooked your event to the click of the submit button. 原因是因为验证是在表单的submit事件上完成的,但您已将事件挂钩到单击提交按钮。 Try this: 尝试这个:

$("#newsletter-form").on("submit", function (event) {
    event.preventDefault();
    // your code...
});

Working example 工作实例

With regard to validating a minimum input length, you can use the pattern attribute: 关于验证最小输入长度,您可以使用pattern属性:

<input type="email" id="footer-grid1-newsletter-input" placeholder="Your Email Address" pattern=".{3,}" required>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM