17 Mar 2010
Check username availability using jQuery and Ajax. Lookup can fire on keypress or button click.
Just use the username text field id as the jQuery selector for the plugin.
$(document).ready(function() {
// default settings
$("#txtUsername").checkAvailability();
});
Here are all of the checkAvailability plugin options and their default values:
// these can all be overridden in your code
target: '#response', // element id where response is displayed
trigger: '#btnCheck', // button id to execute the plugin
ajaxSource: 'test.asp', // URL of the ajax data source
fireOnKeypress: true // execute the plugin as the user types
The plugin also includes a username validation function which uses a regular expression. The input must have a minimum length of 3 and a maximum length of 20 and it can contain letters only. Of course, you can edit this based on your requirements as long as the function returns a boolean value.
function validateUsername(str) {
return (/^[A-Za-z]{3,20}$/.test($this.val()));
};
Also note that your ajaxSource page should also perform server side validation. Once validated server side then you can perform the lookup against your database and write (i.e. PHP echo or ASP Response.Write) the response to be displayed in the id defined in the plugin as the 'target'. A sample ASP page is included in the download.
If you find this resource useful, or if you use this code/plugin on your website, consider tossing a buck, or two, my way to help cover costs!