Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How check if html5 form validation is complete

Tags:

html

jquery

forms

I have a form which am using html5 to validate for email and required fields. The form is to be submitted via ajax. How do i determine that the form passed validation before i allow to form to submitted via ajax.

This is my html:

<form action="" method="post" id="comment_form">
  <input type="hidden" name="post_id" value="<?=$post->ID ?>" />
  <label for="name">Name</label>
  <input type="text" name="name" required="required">

  <label for="email">Email Address</label>
  <input type="email" name="email" required="required">


  <label for="comment">Comment</label>
  <textarea name="comment" required="required" >
  </textarea>


  <label for="submit"></label>
  <button type="submit"class="button green meduim" id="comment_btn">Submit</button>
</form>

This is my jquery

$("#comment_btn").click(function(e){
  //the request url
  var url = site_url+'comments/post_comment';
  //cross site request forgery token
  var xtoken = $("input[name='xtoken']").val();
  //post data
  var dataObj = {
    "name":$('#name').val(),
    "email":$("#email").val(),
    "comment":$("#comment").val(),
    "post_id":$("input[name='post_id']").val(),
    "xtoken":xtoken
  };
  //dim form
  $('#comment_form').addClass('dim');
  //make request
  $.ajax({
    url:url,
    type:'POST',
    data:dataObj,
    dataType:'json',
    error:function() {},
    success:function(resp) {
      if(resp.status == "ok")
      {
        $('#comment_form').removeClass('dim');
      }else {
        alert("An error was encountered");
      }
    }
  });
  e.preventDefault();
});

Is there a way to determine if the form is validated?

like image 693
MrFoh Avatar asked Nov 24 '11 03:11

MrFoh


1 Answers

Don't bind to the click event of the submit button simply bind to the submit event of your form:

$('#comment_form').submit(function(e){
    e.preventDefault();
    //submit via ajax
});
like image 168
alexander farkas Avatar answered Sep 23 '22 06:09

alexander farkas