41

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:

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

$('#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");
        }
    });
});
Sorry-Im-a-N00b
  • 1,151
  • 2
  • 12
  • 20

6 Answers6

62

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

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.

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");
        }
    });
});
csbarnes
  • 1,873
  • 2
  • 28
  • 35
  • 7
    This should be the accepted answer as HTML5 validations are triggered before submit event. Basically, listening on submit event, then preventing default action should do the job. There is no need to invoke the checkValidity() method as shown in accepted answer because if HTML5 validations don't pass, submit event will not be triggered. – Laurent DECLERCQ a.k.a Nuxwin Nov 18 '17 at 05:06
  • Despite what your saying, it get's fired without any kind of validation. Part of my code: $('#begininstall').on('click',function(){ $('#formbegininstall').submit(); }); $('#formbegininstall').on('submit',function(ev){ ev.preventDefault(); var serializado = $('#formbegininstall').serialize(); $.ajax({ – Marcelo Agimóvel Dec 16 '17 at 19:11
  • I can't edit my previous answer. My problem was I was using a link to submit ajax. All I had to do was replace the link by a submit button. – Marcelo Agimóvel Dec 17 '17 at 01:44
57

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");
});
Community
  • 1
  • 1
antinescience
  • 2,339
  • 23
  • 31
4

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.

Musa
  • 96,336
  • 17
  • 118
  • 137
2

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

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;
});
Mfoo
  • 3,615
  • 1
  • 16
  • 11
0

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/

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!

Kurt
  • 311
  • 1
  • 3
  • 9
-2

U can also use jquery validate method to validate form like

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

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

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

Amol
  • 31
  • 6