I’m trying to set up a remote validation with the jQuery validation plugin 1.8.0 (and JQuery 1.5.2).
It works fine for “required” and “maxlength” but the remote validation works ONLY after the 2nd click (validation), or if any of the other errors has been fired before.
The validation is performed correctly and an error message is displayed but the first time, the validation returns true (even if an error is displayed). This is a problem since the form will be submitted with an error.
Here is my code (simplified):
<script type="text/javascript">
$(function() {
$( "#check" ).click(function(){
var valid = $("#myForm").validate(
{rules: {
groupName:{
required:true,
maxlength:40,
remote: {
url: 'ajaxCheck.php', // returns always a dummy string: "Simulate an error message" (JSON encoded)
type: "post",
data: {
groupName: function() {
return $("#groupName").val()
}
}
}
}
}
}
).form();
alert(valid); // Returns true at the first call, and then false
});
});
</script>
<form id="myForm" action="">
<label for="groupName">Group name</label>
<input type="text" maxlength="40" size="45" value="my test" id="groupName" name="groupName">
</form>
<input type="button" value="Check form" id="check" >
The ajaxCheck.php contains:
require_once ('Zend/Json/Encoder.php');
echo Zend_Json_Encoder::encode("Simulate an error message");
The JSON response seems to be correctly encoded (checked with Firebug).
Any idea what I’m doing wrong?
I tried also jQuery 1.6 but had other problems on IE8.
You are not waiting for validation to occur before using the return value. The reason is that validation requires an ajax request, and you’re not waiting for it. The proper way to do this is to include any code you want to run after validation inside of a callback. In the validation plugin there is an
invalidHandlerthat is called when the validation fails. You use it by adding it to the options object that you pass tovalidate()like so:The validation plugin has a number of callbacks that are called based on validation results. Take a look at them here (click on “options” and look for functions that are “callbacks”.)