• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 608
  • Last Modified:

Ajax form submissiona and html5 validation

I am using ajax to submit some form information and I also want to use html5 validation required for my fields.  The code below shows how I am sending my ajax and it works fine.  I just do not know how to check the validation before the ajax starts.

$(document).on('click', '#bill_to_update', function() {	//ajax udate bill to address							   
	var first_name = $('#first_name').val();
	var last_name = $('#last_name').val();
	var address_1 = $('#address_1').val();
	var address_2 = $('#address_2').val();
	var city = $('#city').val();
	var state = $('#state').val();
	var zip = $('#zip').val();
	var address_id = $('#address_id').val();
	var bill_to_update = "yes";
   $('#payment_advanced_box').show().html('<div style="margin-top:15px;"><img src="/loading_25_black.gif"/></div>');
   var url = "/checkout_payment_advanced_include.php";

    $.post(url, {firstName: first_name, lastName: last_name, address1: address_1, address2: address_2, City: city, State: state, Zip: zip, addressID: address_id, billToUpdate: bill_to_update} ,function(data) {

Open in new window

1 Solution
Attach your ajax routine to the form submit action, not a button click i.e. capture when the form is being submitted, prevent the default submission and process your ajax.
I assume you are currently capturing the submit button click.
The form will never submit while HTML5 form validation fails.

$("#myform").submit(function(e) {

Open in new window

Julian HansenCommented:
HTML5 validation can function without javascript - the browser will do this for you. Just add the required attribute to the required fields - see sample below.
<!doctype html>
<script src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
$(function() {
        alert('if you get here the data is valid');
        // do your ajax stuff here
        return false;
<style type="text/css">
    Some value<input type="text" id="fred" required="required"> <br/>
    Some choice <select id="bob" required="required"> <br/>
        <option value="" selected="selected"> Select an option </option>
        <option value="1">1</option>
        <option value="2">2</option>
    </select> <br/>
    <input type="submit" />

Open in new window

LueyAuthor Commented:
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now