Required HTML5 attribute does not work with AJAX feed

I am trying to do some basic validation for a simple newsletter form that is only needed for email. The way I have this form / input inside the page, there really is no place to add any jQuery error messages, so I tried to add a simple HTML 5 attribute, but the form is submitted regardless of whether it is empty.

What would be the best way to add some simple validation to it so that the form checks the email address, does it fill in a minimum 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.
        }
    });
});

enter image description here

+4
source share
1 answer

, submit , . :

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

, pattern:

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

All Articles