I've worked on a fiddle to show the simple validation that I'm trying to do for my user ID field:
- Make it required (validate as aggressively as possible)
- Set a minimum length (validate as aggressively as possible)
- Set a maximum length (validate as aggressively as possible)
- Run an AJAX call to ensure user ID doesn't already exist (I want to only run this on blur)
I'm not using the validate() - remote rule because I wanted to have a custom object returned instead of just a simple string. If that's possible with remote and it only calls the rule on blur, then I can try for that. (All of my AJAX responses adhere to a set object definition.)
HTML
<form action="#" method="get" id="register-wizard">User ID:
<br />
<input type="text" class="form-control required confirm-me" id="User_UserId" name="User.UserId" autocomplete="off" />
<div class="loader user-id hide" style="display: none;"><i class="icon-spinner icon-spin icon-large"></i> (Checking...)</div>
<p>
<button id="next">Next</button>
</p>
</form>
JavaScript
var $wizardForm = $("#register-wizard");
var $validator = $wizardForm.validate({
rules: {
"User.UserId": {
required: true,
minlength: 3,
maxlength: 125,
userIdCheck: true
}
}
});
$("#next").click(function (e) {
e.preventDefault();
//do validations before moving onto the next tab in the wizard
var $valid = $wizardForm.valid();
if (!$valid) {
$validator.focusInvalid();
return false;
}
});
jQuery.validator.addMethod("userIdCheck", function (value, element) {
var validator = this;
this.startRequest(element);
var $loader = $(".loader.user-id");
$.ajax({
url: "/echo/json/",
type: "POST",
data:{
json: JSON.stringify({
text: 'some text'
}),
delay: 1
},
success: function (result) {
console.log("result: ")
console.log(result);
validator.stopRequest(element, true);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("A server error occurred.\n\n" + textStatus);
},
beforeSend: function () {
$loader.show();
},
complete: function () {
$loader.hide();
}
});
return "pending";
}, "The user ID is already in use");
Here's my fiddle: http://jsfiddle.net/eHu35/3/