I am using javascript validation for my input box from javascript-coder and it works fine on my non-ajax pages but when I use ajax to POST inputs the script runs through without stopping even if validation fails. I tried an example from here but when I tried the suggestion the validation didn’t work at all. In my ajax script I can get everything to work with jquery validation by simply putting this in before posting data:
var frm = $(this).closest('form');
if($(frm).valid()){
But I really want to stick with this validation library so I am hoping someone in the community more familiar javascript and maybe even this validation library can help me find an equivalent because I haven’t been able to find anything in all the documentation that allows you to test if validation failed or not before moving my ajax script forward.
My form:
<form method="post" name="send_message_frm" id="send_message_frm">
<div style="margin-top:20px;"></div>
<fieldset>
<div class="clear"></div>
<div style="margin-top:20px;"></div>
<label>Product Group Name:</label>
<input name="desc" class="text-input medium3-input required" type="text" id="desc" value="">
<div style="color:red;" id='send_message_frm_desc_errorloc' ></div>
<div style="margin-top:20px;"></div>
</fieldset>
<input name="user" class="text-input medium3-input" type="hidden" id="user" value="<?php echo $myid ; ?>">
<div style="margin-top:20px;"></div>
<input type="submit" id="send-message" name="submit" value="Send" class='button' />
<div style="margin-top:20px;"></div>
</form>
<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:
<script type="text/javascript">
$(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(
"productgroup_add.php",
data,
function(data){
$("#ajax-loading").hide();
$(frm).find('textarea,select,input').removeAttr('disabled');
$("#send_message_frm").prepend(data);
}
);
}
);
});
</script>
After reviewing the validation script, I discovered (as suspected) that it attaches the validation method to the form’s OnSubmit event handler, which sounds about right…
But… it also attaches itself to the form object:
which has a method that you can call to validate your form:
To run the validations, it looks like you can just do something like: