jQuery Validator Plugin - check for existing Username/Email in mysql database
$.validator.addMethod("checkExists", function(value, element)
{
var inputElem = $('#register-form :input[name="email"]'),
data = { "emails" : inputElem.val() },
eReport = ''; //error report
$.ajax(
{
type: "POST",
url: validateEmail.php,
dataType: "json",
data: data,
success: function(returnData)
{
if (returnData!== 'true')
{
return '<p>This email address is already registered.</p>';
}
else
{
return true;
}
},
error: function(xhr, textStatus, errorThrown)
{
alert('ajax loading error... ... '+url + query);
return false;
}
});
}, '');
OR
You can use the remote method instead which allows you to do remote checks: http://docs.jquery.com/Plugins/Validation/Methods/remote
Eg.
$("#yourFormId").validate({
rules: {
email: {
required: true,
email: true,
remote: {
url: "checkUnameEmail.php",
type: "post"
}
}
},
messages: {
email: {
required: "Please Enter Email!",
email: "This is not a valid email!",
remote: "Email already in use!"
}
}
});
checkUnameEmail.php //Eg.
<?php
$registeredEmail = array('[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]');
$requestedEmail = $_REQUEST['email'];
if( in_array($requestedEmail, $registeredEmail) ){
echo 'false';
}
else{
echo 'true';
}
?>
js code
username: {
required: true,
minlength: 5,
remote: '/userExists'
},
Php code to check if exist and return messages
public function userExists()
{
$user = User::all()->lists('username');
if (in_array(Input::get('username'), $user)) {
return Response::json(Input::get('username').' is already taken');
} else {
return Response::json(Input::get('username').' Username is available');
}
}