最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - HTML5 required attribute not working with AJAX submission - Stack Overflow

programmeradmin2浏览0评论

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.

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?

<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.
        }
    });
});

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.

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?

<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.
        }
    });
});

Share Improve this question edited Mar 1, 2016 at 16:06 Rory McCrossan 338k41 gold badges319 silver badges350 bronze badges asked Mar 1, 2016 at 15:43 PaulPaul 3,3685 gold badges40 silver badges86 bronze badges 5
  • Because Ajax call onclick of a button has nothing to do with the form submission. The browser has no clue that the Ajax call is related to the form. You need to ask if the form is valid or bind to the submit event, not button click. – epascarello Commented Mar 1, 2016 at 15:49
  • also binding to button can be easily bypassed if user submits with keyboard – charlietfl Commented Mar 1, 2016 at 15:54
  • @charlietfl you are referring to putting my button id in my ajax click function, right? $("#footer-grid1-newsletter-submit").on("click", function (event) { . So, should I always bind my form instead? – Paul Commented Mar 1, 2016 at 15:56
  • 2 Not exactly... if user hits Enter on keyboard the submit event of form triggers but not click on button. Forget about the button – charlietfl Commented Mar 1, 2016 at 15:58
  • @charlietfl Gotcha! Great advise. Thank you! – Paul Commented Mar 1, 2016 at 16:00
Add a comment  | 

1 Answer 1

Reset to default 21

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. 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:

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

评论列表(0)

  1. 暂无评论