jQuery Ajax Validation Use the Remote Rule
I only just found out that the jQuery validation plugins has a validation rule called “remote” which can be used to make an ajax request instead of specifying a custom rule which has an ajax call it in. This will save you heaps of time with those custom validation rules. Basic jQuery Form Validation Tutorial (2mins).
Example: Checking if a users email is already registered.
The new remote method way
As you can see to pass through data you can simply use the key pair syntax so the request sent below the data is “&emails=email@jquery4u.com”. The return values for your backend script is either json encoded true for a validation pass or html msg for validation fail.
//VALIDATE USER EMAIL
$(':input[name="uAcc"]').rules("add",
{
"remote" :
{
url: 'validateEmail.php',
type: "post",
data:
{
emails: function()
{
return $('#register-form :input[name="email"]').val();
}
}
}
});
The old add custom method way
//VALIDATE USER EMAIL
$.validator.addMethod("validateUserEmail", 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(data)
{
if (data !== 'true')
{
return 'This email address is already registered.
';
}
else
{
return true;
}
},
error: function(xhr, textStatus, errorThrown)
{
alert('ajax loading error... ... '+url + query);
return false;
}
});
}, '');
$(':input[name="email"]').rules("add", { "validateUserEmail" : true} );
Backend PHP Script
real_escape_string($_POST['email']);
$query = "SELECT ID FROM users WHERE user_email = '{$email}' LIMIT 1;";
$results = $mysqli->query($query);
if($results->num_rows == 0)
{
echo "true"; //good to register
}
else
{
echo "false"; //already registered
}
}
else
{
echo "false"; //invalid post var
}
?>
Another Example to help
/* register script */
(function($,W,D,undefined)
{
$(D).ready(function()
{
//form validation rules
$("#register-form").validate({
rules:
{
email:
{
required: true,
email: true,
"remote":
{
url: 'validateEmail.php',
type: "post",
data:
{
email: function()
{
return $('#register-form :input[name="email"]').val();
}
}
}
},
name:
{
required: true,
minlength: 3
},
password:
{
required: true,
minlength: 8
},
password_repeat:
{
required: true,
equalTo: password,
minlength: 8
}
},
messages:
{
email:
{
required: "Please enter your email address.",
email: "Please enter a valid email address.",
remote: jQuery.validator.format("{0} is already taken.")
},
name: "Please enter your name.",
password: "Please enter a password.",
password_repeat: "Passwords must match."
},
submitHandler: function(form)
{
form.submit();
}
});
});
})(jQuery, window, document);
Stopping remote validation as you type
By default the validation plugin will send off an ajax request for a remote rule every key you press causing too many ajax requests being sent to validate fields. One way to disable this is to deactivate the onkeyup validation so that the remote rule is only validated via ajax once you have finished typing into the input.
$("#register-form").validate({
onkeyup: false //turn off auto validate whilst typing
});