Monday, April 23, 2012

Need if / then statement for javascript validator

With Jquery validator I'm able to use the following if statement to be sure my form is valid before proceeding with Ajax:



var frm = $(this).closest('form');        
if($(frm).valid()){
AJAX JQUERY POST INFORMATION GOES HERE
};


Now I am using Javascript Form Validator from Javascript-Coder.com. The problem is none of the documentation describes a similar function to valid() or a way to check to see if the form is valid before proceeding. I am limited in javascript and could really use help from the community to build a similar if statement.



I am running the validation just fine but even when the validation fails my ajax script continues to run through to completion. In non ajax applications the validation works great and stops automatically before posting to php. But with ajax I can't seem to stop the script when validation fails to allow my user to correct their action.



I tried gleaning something from Here but it didn't get me close enough to do something useful. I tried some variations of what was offered there but I'm missing something.



My validation works great and is:



<script  type="text/javascript">
var frmvalidator = new Validator("send_message_frm");
frmvalidator.EnableOnPageErrorDisplay();
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("desc","alnum","Only numbers and letters are allowed");
frmvalidator.addValidation("desc","req","Please enter a description");
</script>


My ajax script works as well but I need it to not run if validation fails. It is:



$(document).ready(function(){
//Validate form....what can I put here to test if validation is completed properly????

//onclick handler send message btn
$("#send-message").click(function(){
$(this).closest('form').submit(function(){
return false;
});
var frm = $(this).closest('form');

$("#ajax-loading").show();
var data = $(frm).serialize();
$(frm).find('textarea,select,input').attr('disabled', 'disabled');
$.post(
"company_add.php",
data,
function(data){
$("#ajax-loading").hide();
$(frm).find('textarea,select,input').removeAttr('disabled');
$("#send_message_frm").prepend(data);
}
);
}
);
});
</script>




No comments:

Post a Comment