Ajax Form Validation With HTML5

Tags: html5 ajax javascript jquery

Html 5 is a beautiful thing. Especially when dealing with a lot of the annoyances of web development, like form validation. Below is a quick tutorial on how to submit a form using ajax, while taking advantage of the built-in browser form validation.

First, we start off with a form:

 <form id="form1" action="/MySite/NewPerson" method="post">
    <label>First Name</label>
    <input name="fname" type="text" required />
    <label>Last Name</label>
    <input name="lname" type="text" required />
    <label>Email</label>
    <input name="email" type="email" required />
    <label>Phone</label>
    <input name="phone" type="tel" required pattern="^[\d]{3}-[\d]{3}-[\d]{4}$" />

    <button type="submit">Submit</button>
</form>


By default, the above form will be validated by the native browser. If the browser is fully html5 compatable, it will show error messages on form fields that are not completed correctly, and prevent the form from being submitted without all the required fields in the correct format.

But what if you want to submit the form via ajax? Well, you're in luck! You can leverage all of the built-in html5 form validation by overriding the submit event in javascript.

Using jQuery:

 <script type="text/javascript">
    $("#form1").submit(function() {
        $.ajax({
            type: "post",
            dataType: "",
            url: "/MySite/NewPerson",
            data: $("#form1").serialize(),
            success: function(response) {
                $("#form1").html(response);
            }
        });
        return false;
    });
</script>


The above snippet will allow the browser to continue with its default validation behavior. The submit event will not be triggered until the form validation requirements have been met.

Win!!!

Good Related Reads:
Html5 form validation overview
Backwards compatability for html5 form validation

Add a Comment