ASP.NET AJAX username availability check
AJAX, ASP.NET, CSS, UI By Dave Ward; Updated October 10, 2008
When you have a name as common as mine, you run across the entire gamut of schemes to deal with username availability in membership systems. By availability, of course I mean denial and rejection. Out of all of the ways that I’ve had “Dave” rejected, inline AJAX verification is definitely the least annoying. Wanting to be less-annoying myself, I’ve added the same functionality to my ASP.NET AJAX sites. Let me show you how I did it.
Note: I will preface this example by saying that an UpdatePanel is not the most efficient possible way to solve the problem. Using a web service or page method is much lighter over the wire. However, for the vast majority of sites, this method is perfectly suitable and much easier to work with.
Setting up the page.
For this example, I’m going to use a very simple registration form:
Username: <asp:TextBox runat="server" id="Username" /><br /> Password: <asp:TextBox runat="server" ID="Password" /><br /> Confirm: <asp:TextBox runat="server" ID="PasswordConfirm" /><br /> <asp:Button runat="server" ID="Button1" Text="Sign me up!" />
Since I want to work with it asynchronously, I’m going to wrap the Username TextBox in an UpdatePanel. I’m also going to enable AutoPostBacks on it and handle its OnTextChanged event. Inside an UpdatePanel, this will cause a partial postback to the event handler any time the TextBox loses focus and its contents have changed.
<asp:UpdatePanel runat="server" ID="up1"> <ContentTemplate> Username: <asp:TextBox runat="server" id="Username" AutoPostBack="true" OnTextChanged="Username_Changed" /><br /> </ContentTemplate> </asp:UpdatePanel>
Note that I only wrapped the username line in the UpdatePanel. If the entire form were in an UpdatePanel, the returning partial postback would revert all of the form fields to their values when the postback initiated. That behavior would be undesirable here, where users will likely be tabbing through the form quickly and might complete several other fields during the partial postback.
Checking username availability
I decided to check availability through a call to Membership.GetUser(). If a user with the supplied name exists, the method will return the corresponding MembershipUser. Otherwise, it returns null. With this in mind our OnTextChanged event handler is easy:
protected void Username_Changed(object sender, EventArgs e) { if (Membership.GetUser(Username.Text) != null) // Display a username taken message. else // Display a username available message. }
This method should work with any .NET Membership Provider setup, regardless of your data store or other customizations. Obviously, if you’re using a custom authentication system instead of the .NET Membership Provider, then you’ll need to perform the availability check a different way.
If anyone knows of a more efficient method for checking the username availability, I’d be interested in hearing it. Returning an entire MembershipUser object to express (in this case) what boils down to a boolean value is painfully wasteful.
Displaying the availability result
I chose to display my message in a div, just to the right of the username field:
<asp:UpdatePanel runat="server" ID="up1"> <ContentTemplate> Username: <asp:TextBox runat="server" id="Username" AutoPostBack="true" OnTextChanged="Username_Changed" /> <div runat="server" id="UserAvailability"></div><br /> </ContentTemplate> </asp:UpdatePanel>
With that element now accessible, I can complete the Username_Changed event handler:
protected void Username_Changed(object sender, EventArgs e) { if (Membership.GetUser(Username.Text) != null) { UserAvailability.InnerText = "Username taken, sorry."; UserAvailability.Attributes.Add("class", "taken"); } else { UserAvailability.InnerText = "Username available!"; UserAvailability.Attributes.Add("class", "available"); } }
The relevant CSS:
#UserAvailability { padding-left: 22px; background-position: left; background-repeat: no-repeat; } .taken { background-image: url(taken.gif); } .available { background-image: url(available.gif); }
The CSS classes, taken and available, are used to display a left positioned background image in the div (as seen in the screenshot above). The left padding ensures that the text message doesn’t overlap the status image. This visual cue is very powerful, and should not be overlooked.
That’s it!
In my production code, I’ve added a couple usability improvements: a progress indicator while the availability check is in progress, and changing the submit button’s enabled property depending on availability. I’ve detailed how I implemented those additional features in a follow-up post here: User availability check usability improvements.
Similar posts
What do you think?
I appreciate all of your comments, but please try to stay on topic. If you have a question unrelated to this post, I recommend posting on the ASP.NET forums or Stack Overflow instead.
If you're replying to another comment, use the threading feature by clicking "Reply to this comment" before submitting your own.
3 Mentions Elsewhere
- ASP.NET AJAX username availability check « Wiki ASP.NET
- Искусство и программерский dzen » Проверка имени на занятость.
- coder99 » ASP.NET AJAX username availability check



Hai, It was really helpful for me learn Ajax with your code. This is the first code in Ajax I’ve seen and I implemented your example and it worked. I’ve tried with another method. Instead of using Membership records, I’ve used the db records to check the availability. May be you might know this, but this is my first try. So I feel happy to do something new of my own. The code goes below:
Everything same, but change in default.aspx.cs
protected void Username_Changed(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(“Server=achuthakrishnan; Initial Catalog=achu; Integrated Security=SSPI”);
SqlCommand cmd = new SqlCommand(“select * from users”, conn);
conn.Open();
SqlDataReader dr;
System.Threading.Thread.Sleep(3000);
dr = cmd.ExecuteReader();
while (dr.Read())
{
if (TextBox1.Text == dr["username"].ToString())
Label1.Text=”Username already exists”;
else
Label1.Text = “Username available you acki”;
Thanks again,
ak
That will work, but you may find it more efficient to query the database for the entered name to see if it exists, rather than comparing it with every username in a loop. If you have 100,000 users, you could be waiting a while :-)
hay can u get me the whole code including the database.every thing is find working but it is not geting correct result back.Its showing me Available Message for every user and non user .
Hi,
This code is helpful to me.Thanks for this code.
Thank u very much.
i use username check availabilty,if i enter the letters inthe text box ,if it is avail or not,display inthe label doesn’t click the button event,please sent the code
i use this code,check username avail or not, if i enter the letters in the username text box ,at the time answer will display in the label,doesn’t click the button or any other event,send this code
Its showing me Available Message for every user and non user .Please tell me what is the error.
That might happen if you’re not using the ASP.NET membership services. This technique relies on that for the user availability check.
Hello,
This post was really helpful!
But how did you manage to place div “UserAvailability” line-in-line with TextBox “Username”???
You can download the full source for the example on this page.
I checked this code. But unfortunately the particular page client side validation is not working. So give me the solution also.
the code as given by u with few changes is not wrking
i am using access2003 database and asp.net with vb code behind
used te following code in codebehind page
Public Sub Username_Changed(ByVal sender As Object, ByVal e As EventArgs)
msgbox(“hello”)
If Membership.GetUser(Username.Text) IsNot Nothing Then
MsgBox(“Exists”)
UserAvailability.InnerText = “Username taken, sorry.”
‘ UserAvailability.Attributes.Add(“class”, “taken”)
Else
UserAvailability.InnerText = “Username available!”
‘ UserAvailability.Attributes.Add(“class”, “available”)
End If
End Sub
but when focused out of text box nothing happens
in this the hello msg is displayed but no msg as per the textbox value.
can u tell whts the mistake
used the following code depending on above but no msg is displayed
can anybody tell whts the mistake
hello msg is displayed but after that nothing
Public Sub Username_Changed(ByVal sender As Object, ByVal e As EventArgs)
MsgBox(“hello”)
If Membership.GetUser(Username.Text) IsNot Nothing Then
MsgBox(“Exists”)
UserAvailability.InnerText = “Username taken, sorry.”
‘ UserAvailability.Attributes.Add(“class”, “taken”)
Else
UserAvailability.InnerText = “Username available!”
‘ UserAvailability.Attributes.Add(“class”, “available”)
End If
End Sub
Do you have an ASP.NET Membership Provider for your Access database? If you’re just using an ad-hoc “users” table in Access, Membership.GetUser() won’t work.
My version of this is currently not working in Google Chrome 0.4.154.29 (latest currently out) although it does work in Firefox, IE7, and Opera (also based on WebKit). I’ll debug it at some point (probably a bug in Chrome), but it isn’t too high a priority for now. If anyone else has seen this problem and figured out a fix, please let us know.
Thanks
It’s Really Good….
if i have to check username and email then what can i do in add_initializeRequest(InitializeRequest) of page request manager? if i do not want both waiting for process of username and email run at the same time?
I would recommend using a web service or page method. They both allow multiple requests to run simultaneously.
gonna try this with sql server and asp.net ajax today
thanks for the tutorials
Thanks, just what I was after.
Its very nice and simple to use…
Great work. Thanks.
Good but it is much better if you pass text of text box in where condition in query.. just check if it returns any rows it is not available else it is available.. No need to get all rows and then checking…
hiii Dave Ward, I have followed your code,it is working fine without membrship also.But I found that if some body copy and paste the user name int the textbox without using keyboard than what happened please tell me I am waiting for reply.
There’s not an easy way to detect paste events in the DOM. It should still work after they change focus from that field though.
this post is useful for me,by using this post i am checking file exist or not.
I just tried this in a custom dotnetnuke module. I got it to work..simple enough. However I have an annoying problem, the image gets slightly cropped on the top and bottom. My image similar to the to the green and red check that is show on your sample at the top of this page. Any ideas? Thank you
There might be some styling on your form that’s giving the UpdatePanel div overflow: hidden. You can dig into that pretty well by inspecting it in Firebug and looking at how it highlights the element’s box model.
The easiest solution might be to resize your images to fit the visible area.
Can you send me a link to a site where I can see the end result in action?
There’s not much to it. It either displays the “taken” or “available” icon depending on what Membership.GetUser() returns. If you follow the link to the next article in the series, there’s a source download that you can run and see in action.
Hi Dave!
I’ve tried your User Name checking technique and its perfect. But my requirement is slightly changed. I’ve more than 1 fields on my form to check for availability. I need to check the availability of User Name, Email and Authenticate a Key. I placed the all 3 divs in my form along with corresponding divs and also wrote OnTextChanged events for all 3 fields. Moreover, I’ve done the same in InitializeRequest with other 2 fields like done for User Name. Problem starts here now, as when text changes for any of these 3 fields, all 3 divs go to “checking” state and shows checking status on page. How can I make it to show only corresponding field’s “checking” status and hide the other 2 at that time?
Thank You,
Mudasser Hassan
The problem there is probably that only one UpdatePanel refresh can be in progress at any given time. So, if you tab through and complete those three fields quickly, the concurrency issues will cause trouble.
If it were me, at this point, I would probably use jQuery Validation’s remote validation feature to validate against a web service or page method. That way, more than a single validation could take place simultaneously.
Hi Dave!
Thank you very much for your reply.
I’ve checked for the possible issues you talked about. I experienced no concurrency issue even if tab through and very quickly complete those three fields. All fields are validated/authenticated successfully isolated and within their scope; no collapse, ambiguity or any other issue at all.
The problem is only with InitializeRequest method, because here we are assigning css class and changing text of all three “authentication message” divs. So, each time, when any of the three fields data is changed, all three divs shows “checking” status. 1 more thing I want to clear, this happens only in “checking” state otherwise it only shows the only 1 corresponding div for “authenticate” or “failed” message, not all 3 divs (as you know we’ve a separate OnTextChanged method for each of the text field and changing only that div’s class and text within that methods, not the other remaining 2).
Can you share some trick to control the “checking” state message?
Thank You,
Mudasser Hassan
I see what you’re talking about now. I was confused because this post doesn’t deal with the “checking availability” indication; that’s in a later post.
What you’ll need to do is detect which TextBox raised the event in your initializeRequest handler and target the $get() at the appropriate element accordingly. It’s been a long time since I’ve worked with those events, but I believe the
argsparameter has a postBackElement property which you can use to determine that. The best thing to do would be using a client-side debugger like Firebug to set a breakpoint in that initializeRequest handler and inspect the value ofsenderandargswhen you change the data in one of those fields.Good one.. thanks a lot
This is a really very helpful tutorial