Check username availability with ASP.NET AJAX
Many sites these days show if a specific username is available or not when users are filling out the registration form. AJAX is being used to accomplish this task. After seeing an example demonstrate this using PHP, i wanted to do the same with the ASP.NET AJAX. As it turned out it is very easy to do it with the ASP.NET AJAX Framework.
The technique that will be used in this example depends on using PageMethods. PageMethods allow us to call these static (or Shared) methods from client side javascript. These static methods are available to a specific ASPX page. The other alternative is to create an .asmx file and then call the webservice from javascript.
In this example, i use the Membership provider to retrive the username from the SQL Server 2005 database. You'll need a page with a registration form on it. You can see my registration form and a working example of the username check here: http://riderdesign.com/users/register.aspx. You will also need a cool animated gif which we will display when we check the username availability. You can find and make your own ajax loading gif here: http://www.ajaxload.info
The following WebMethod uses the Membership.GetUser function find the username in the database if it exists. If the username exists we return true and return false it it does not. We will use these values in our javascript to show whether or not the username is available. The second webmethod checks for a duplicate email address. This is useful is you are enforcing the unique email policy in the web.config using requiresUniqueEmail="true"
<Services.WebMethod()> Public Shared Function CheckUserName (ByVal userName As String) As Boolean
' System.Threading.Thread.Sleep(2000) Use this to sleep so we can see the cool ajax gif play for a bit
If (Membership.GetUser(userName) IsNot Nothing) Then
Return True
Else : Return False
End If
End Function
<Services.WebMethod()> Public Shared Function CheckEmail(ByVal email As String) As Boolean
System.Threading.Thread.Sleep(5000)
If (Membership.GetUserNameByEmail(email) IsNot Nothing) Then
Return True
Else : Return False
End If
End Function
In the Page_Load of the code behind I added the following code. This code adds the onblur event to the Usename and Email text boxes so that the javascript functions to check username availability and to check for duplicate email address will fire when the user clicks on another textbox.
Username.Attributes.Add("onblur", "CheckUserName()")
Email.Attributes.Add("onblur", "CheckEmail()")
In this sample i chose not to use the createuserwizard and instead manually lay out my registration form. I wanted complete control over the layout and did not want the table based layout the the createuser wizard generates. In the registration page we need two empty spans - one that alerts the user we are checking username availability and the other alerting him or her we are checking for a duplicate email address. These spans are given the IDs spanUsername and spanEmail respectively, and will be next to the Username and Email textboxes. Our javascript will control the html of these spans using the innerHTML property. In your registration page include the following javascript:
var txtUserName;
var txtEmail;
function pageLoad()
{
txtUserName = $get("<%=Username.ClientID %>");
txtEmail = $get("<%=Email.ClientID %>");
}
In this block of code, 2 variables are declared. We use the $get syntax which provides a shortcut for getElementById. Also i used UniqueID for the Username and Email fields since these textboxes have $ in their IDs. The ClientID returns the IDs with the underscore character. My page is a content form and thus subject to the ID mangling that occurs when using master pages. I hope this tidbit helps a lot of developers since i bet most are using master pages. The next bit of javascript we need is the one for checking the username. Our CheckUserName function will run when the user clicks out of the username textbox thansk to the onblur event. We also want it to run only when there is text in the textbox hence the txtUserName.value.length >0. Using the innerHTML property we display a notice to the user that we are checking if the desired username is available as well as including a cool little animated gif. We then call the CheckUsernameFunction and pass in the username value.
function CheckUserName()
{
if (txtUserName.value.length > 0)
{
$get("spanUsername").innerHTML = "Checking Username Availability...<img id=imgWaiting src=../images/ajax-loader.gif>";
$get("spanUsername").style.color = "red";
$get("spanUsername").style.fontWeight = "bold";
PageMethods.CheckUserName(txtUserName.value, OnCheckUserName);
}
else
{
$get("spanUsername").innerHTML= "";
}
}
The next chunk of JS is the OnCheckUserName function. If the username is not available we inform the username is not available with a little bit of styling and conversely if available politely tell the user his desired name is available.
function OnCheckUserName(unavailable)
{
if (unavailable == true)
{
$get("spanUsername").innerHTML = "Username Unavailable";
$get("spanUsername").style.color = "red";
$get("spanUsername").style.fontWeight = "bold";
}
else if (unavailable != true)
{
$get("spanUsername").innerHTML = "Username Available";
$get("spanUsername").style.color = "green";
$get("spanUsername").style.fontWeight = "bold";
}
}
The block of JS for checking for a duplicate email address is very similiar to what we just did for the username.
function CheckEmail()
{
if (txtEmail.value.length > 0)
{
$get("spanEmail").innerHTML = "Checking for duplicate email...<img id=imgWaiting src=/images/ajax-loader_small.gif>";
$get("spanEmail").style.color = "red";
$get("spanEmail").style.fontWeight = "bold";
PageMethods.CheckEmail(txtEmail.value, OnCheckEmail);
}
else
{
$get("spanEmail").innerHTML= ""
}
}
function OnCheckEmail(duplicate)
{
if (duplicate == true)
{
$get("spanEmail").innerHTML = "Email has already been used";
$get("spanEmail").style.color = "red";
$get("spanEmail").style.fontWeight = "bold";
}
else if (duplicate != true)
{
$get("spanEmail").innerHTML = "Nonduplicate Email Address";
$get("spanEmail").style.color = "green";
$get("spanEmail").style.fontWeight = "bold";
}
}
Using Ajax, we can easily inform a user (while filling out the registration form) if the desired usenrame is available as well as letting him or her know if their email has already been used to register a new account. Using this approach is a perhaps bit more work than using an update panel and you do need to dust off those javascript skills. Overall, we can use Ajax to create more informative and engaging user interfaces.
Addendum: I found a slight error in the above code. In the CheckEmail and CheckUsername functions io left off the curly braces that should be around the else clause. Without them the javascript will not work in Firefox. Also you do need to use ClientID to get the client ID of the controls. UniqueID will only work in IE and not in FF. In IE the ajax loading gif will stay on the same line as the messages indicating whether theusername/email address is being checked. In Firefox CSS is needed to get the image to line up on the same line. I used vertical-align: 58%; for firefox. But IE will not obey this rule so i used IE conditional comments and this CSS vertical-align: middle;.
Download the source files