I\'m coming into the middle of this project so I\'m having to do a bit of re-writing because of sloppy code. I am using jQuery 1.6.1 and Validate 1.8.1.
First, here\
I faced the same problem, But I find the easiest solution just return true or false after encoding into json through php.
if ($users->username_exists())
{
echo json_encode(FALSE);
}else{
echo json_encode(TRUE);
}
On your server side script, try returning true
or false
instead of available
and notavailable
, as both of those strings are equivalent to true
.
While you adding addMethod you should return true or false from server side.
and also that value have to be returned from addMethod.
ie something like this
$.validator.addMethod("checkAvailability",function(value,element){
var parameter="action=checkusername&username="+username;
$.ajax({
url: "dbquery.php",
type: "POST",
async: false,
data: parameter
success:function(output)
{
return output
}
});
},"Sorry, this user name is not available");
Check when the validation function is getting called, what the value of username
is and what the value of output
is: is it true
or "true"
?
I'm guessing latter: a string, so you could just do:
return output === "true" ? true : false; // I sincerely recommend using === here
Since if you return "false";
will evaluate to true
because it's a non-empty string - yay dynamic langauges! :/
Example with remote
:
$("#signup").validate( {
rules: {
username: {
required: true,
minlength: 5,
remote: {
url: "dbquery.php",
type: "get",
data: {
action: function () {
return "checkusername";
},
username: function() {
var username = $("#username").val();
return username;
}
}
}
}
},
messages: {
username: {
required: "Enter a username"
}
},
submitHandler: function(form) {
form.submit();
}
});
To set a custom error message your PHP file must return the message instead of false, so echo "Sorry, this user name is not available"
in your PHP file.
My code:
$( "#myform" ).validate({
rules: {
EMAIL: {
remote: {
type: "post",
url: "checkMail.php",
data:{checkUsername:function(){return $("#EMAIL").val()}
}
}
}
},messages:{EMAIL:{remote: "Already taken!"}}
});