MrFoh MrFoh - 4 months ago 16
HTML Question

How check if html5 form validation is complete

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?

Answer

You can use the validator's form() function, e.g.

var validator = $("#comment_form").validate(options);
if (validator.form()) {
    // submit with AJAX
}
Comments