Here is another jQuery tutorial demonstrating how to perform text validations using jQuery’s blur() event.
Its a fact that client-side client validation is no alternative to server-side validation especially in web applications. However, that doesn’t mean that we should drop client-side validation altogether. The truth is that client-side validation enhances a web application. First, the client-side validations provide a more responsive interface for users. Secondly, for a very large enterprise-grade application, shifting some of the validations on the client as a first pass filter will reduce the load on the server and improve its performance.
Now let’s move on to the tutorial. First of all, I’m going to use a simple registration form as an example for validation. Here is the demo for this tutorial:
Username: Username must be at least 4 characters in length
Password: Password must be at least 6 characters in length
Here is how the form looks like in code view:
<b>Username:</b> <i>Username must be at least 4 characters in length</i>
<input type="text" id="txt_username" name="username">
<span id="username_warning" style="color:red"></span>
<b>Password:</b> <i>Password must be at least 6 characters in length</i>
<br><input type="password" id="txt_password" name="password">
<span id="password_warning" style="color:red"></span>
In the example above, we’ve created a span for where our error message will appear with a unique id so they can be selected later on. What is important in this form is that we assign an id for each of the fields we need to validate so we can bind it with its corresponding jQuery event. Since we want to validate the text boxes once a user has supplied an input, the events of choice here will be both the change() and blur() event. However, the change() event has problems when the user reloads the page. Even with an invalid input, the validation will not trigger unless the user has changed the value of the input itself.
Now to validate the length of the user input, we must find the length of the text fields using the jQuery selectors. Here is how to do it:
$(document).ready(function(){
$("#txt_username").blur(function()
{
var username_length;
username_length = $("#txt_username").val().length;
$("#username_warning").empty();
if (username_length < 4)
$("#username_warning").append("Username is too short");
});
$("#txt_password").blur(function()
{
var password_length;
password_length = $("#txt_password").val().length;
$("#password_warning").empty();
if (password_length < 6)
$("#password_warning").append("Password is too short");
});
});
If you want to view the tutorial, you can download it here below:
Textbox Validation and the blur() Event Demo Download









