Check Username Availability with ASP.NET AJAX

Here is a little trick you can use to spice up your registration pages. I will use ASP.NET AJAX to inform the user whether the username they have entered is available. Rather than use the UpdatePanel, I will slim down the amount of data going over the wire for each ajax request. I will accomplish this using the PageMethods feature.

This tutorial assumes that you have a working knowledge of how to start an ASP.NET AJAX web application, drop a script manager control onto your form, and use the CreateUser wizard control, or another method of registering users.  A little JavaScript knowledge will help too.

In order to use PageMethods, I will need to set the EnablePageMethods property to true on my ScriptManager.

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True" />
My registration page is called register.aspx. I will create a static method in the code behind for this page. The method will check to see if a username exists, and return a Boolean indicating whether the username is available or not.
public static bool IsUserAvailable(string username) 
    MembershipUser usr = Membership.GetUser(username);
     return (usr == null);

The WebMethod attribute is needed to mark this as a method that can be executed from Javascript.

Now I will go ahead and create some markup create some markup for my username field on your registration page. Something like this should do.

<asp:Label ID="lblUserName" runat="server" AssociatedControlID="UserName">Desired Username</asp:Label>
<asp:TextBox ID="UserName" runat="server" CssClass="txt" onkeyup="usernameChecker(this.value);" />
<span id="spanAvailability"></span>

There are a couple of things to take note of here. The onkeyup javascript event will be fired every keypress, and will be used to check the availability of the username entered.  Also take note of the span with an id of spanAvailability. The JavaScript will use this span to write output letting the user know whether the username is available.

Here's the last part, the Javascript that wires everything together.  I will insert this at the bottom of my register.aspx page:

<script type="text/javascript">
var usernameCheckerTimer;
var spanAvailability = $get("spanAvailability");

function usernameChecker(username) 
    if (username.length == 0)
        spanAvailability.innerHTML = "";
        spanAvailability.innerHTML = "<span style='color: #ccc;'>checking...</span>";
        usernameCheckerTimer = setTimeout("checkUsernameUsage('" + username + "');", 750);

function checkUsernameUsage(username) 
    // initiate the ajax pagemethod call
    // upon completion, the OnSucceded callback will be executed
    PageMethods.IsUserAvailable(username, OnSucceeded);

// Callback function invoked on successful completion of the page method.
function OnSucceeded(result, userContext, methodName) 
    if (methodName == "IsUserAvailable")
        if (result == true)
            spanAvailability.innerHTML = "<span style='color: DarkGreen;'>Available</span>";
            spanAvailability.innerHTML = "<span style='color: Red;'>Unavailable</span>";

This effect is pretty easy to do, and adds a nice value to the user experience.  I hope you are able to find use for this technique in your applications.

Update: Download a sample project here

Unit next time,



  • It's about time you joined the blogosphere. I'm looking forward to your bloggin future :)

  • Awesome post!! This really was the first time I've had any exposure to PageMethods! Keep up the great postings!

  • I found that PageMethods are nice for "small/encapsulated" tasks like this. For use with anything that needs access to your Page fields its tricky, because the pagemethods are static methods.

    For anything "more complex" WCF in .NET 3.5 is nice since you can make similar Javascript/JSON calls now...something that WCF 3.0 was missing.

  • Nice implementation -clean and simple, just the way I like it. I've been thinking about doing this for a site I'm working on just to "spice up" the registration page.

  • Nice post travis.

  • Is it only me??
    Im getting a full postback
    Its not the way it is supposed to work, is it?

  • Alexei, no you shouldn't be getting a postback. I'll make an example project and post it on here.

  • I have posted a sample project here:

  • function checkUsernameUsage(username)
    // initiate the ajax pagemethod call
    // upon completion, the OnSucceded callback will be executed
    PageMethods.IsUserAvailable(username, OnSucceeded);

    PageMethods is undefined?

  • @macupryk

  • hi
    how can i use my database for it...

    Very nice job...

    Keep it on...

    Thanx a lot

  • Ok Thanks I got How to do with My database....

    I have done it as

    public int CheckUserAvailability()

    MainClass ObjMainCls = new MainClass();
    SqlCommand Cmd = new SqlCommand("Portal_CkeckUseravail");
    Cmd.CommandType = CommandType.StoredProcedure;
    Cmd.Parameters.Add("@Uname", SqlDbType.NVarChar,50).Value = this.Name;
    SqlDataReader Reader = null;

    SqlParameter parameterUserVal = new SqlParameter("@Avail", SqlDbType.Int);
    parameterUserVal.Direction = ParameterDirection.Output;
    int i = ObjMainCls.ExecuteNonQuery(Cmd);
    return (int)parameterUserVal.Value;


    Thank you very much

  • hi
    this code is for c#,can you show haw work in vb.thank`s

  • i treid using the code , i am using as code behind
    tried to change the code but getting error

    culd u assist

    in code behind page i used
    Public Shared Function IsUserAvailable(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

    and rest as given by you
    i amgetting error "page method not defined"
    and onkeyup is not an event of textuser

    and how do i check it with access2003 database

  • I tried the code with VB.NET. I am getting an error "Microsoft JScript runtime error: 'PageMethods' is undefined"

    Can anyone help?

  • I was trying to use the check availabity in my project
    I am having one master that has script manager ok.
    when i try to use another script manager i am getting the error that project must one script manager.because the page in which i am using the check availability is inherited from that master page.
    when i remove the script manager in the master and added the script manager in the aspx page.

    I am getting the script
    error the spanavailability is null or not an objecy

  • Thanks ,I solve my big problem

  • Hi Travis,

    I am getting a javascript error which says 'spanavailability is null or not an object'.

    I am using IE 8.

    Thnx in advance.


  • Travis,

    This is exactly what I was looking for and totally rocks!! Thanks for the PageMethods tip!

  • Could not fine "spanAvailability" in javascript

  • Great Post...! it works for me.

    Thanks a lot..!

  • get error with spanAvailability

    Also it doesnt seem to work with firefox.

  • I got everything to work with FF and Chrome by moving the span declare:
    var spanAvailability = $get("spanAvailability");

    to within each function rather than leaving it as global variable.

  • Thanks a lot for this, it's awesome!

  • Not working with FF for me, I have tried @chris idea but to no avail

  • Hey Its not working in IE Either.Hey Jamie,Were u able to get it it.Even i m getting the same error of Span Availability

  • simply superb..
    thanks a lot

  • Got this error:

    Your code is working on separate page but when this code is merged on my page , got following error.

    The server method 'IsUserAvailable' failed with the following error: System.NullReferenceException-- Object reference not set to an instance of an object.

  • Nice work!


  • Thanks man, I will be using it on my site with your permission. One question though, where can I learn all of this :$?

  • YES! Exactly what I was looking for. Nice and clean and simple... :) Many Thanks

  • Doubt is the key to knowledge.


  • You have to believe in yourself . That's the secret of success.


  • PageMethods

    I have enabled page methods in my root master page.

    Line: 531
    Error: 'PageMethods' is undefined

    I have this in a user web control ascx.

    I am not sure how to get around this.

    If someone can help me. that would be great.

  • -----------------------------------------------------------
    "Great publish & Fantastic weblog! I would definitely love to begin a blog too but I have no clue where to begin. I possess the ability to do it (not that challenging on the technical part) but I truly feel like I'm too lazy to publish regularly. That is the problem, if you start you have to go all the way. However blogs like yours inspire me to possess a go at it. "

  • Thanks a lot for this :')

  • its working for a single text but i am comparing with database field ,,,so span ("Checking...") is displaying and no result is displaying whether it is available or not???

    Pls Ans Me As Soon As Possible....


  • This code is not execute in .NET 3.5? How to execute .NET 3.5? help me...

  • i have been used these type of code.. but i got an error - not all code path returns a value..

    can u send how to get & check username frm database..

    public static bool IsUserAvailable(string username)

    string returnValue = string.Empty;

    SqlConnection con = new SqlConnection("data source=CSRN014\\SQLEXPRESS;initial catalog=gv;integrated security=true;");
    SqlCommand cmd = new SqlCommand("spx_CheckUserAvailability", con);
    cmd.CommandType = CommandType.StoredProcedure;
    SqlDataReader dr = cmd.ExecuteReader();

    while (dr.Read())
    if ((username.ToLower() == dr.GetValue(0).ToString()))
    return false;
    return true;



  • it always returns unavailable even if username does not exist in the database.. :( please help.

  • Extremely beneficial posting Excited for extra content articles inside your internet site.

  • I found this post useful when working on a registration page today. Thanks.

  • I am Geting Error

    spanAvailability not avaialble

    pls help me

  • Message: 'spanAvailability' is null or not an object
    Line: 576
    Char: 17
    Code: 0
    URI: http://localhost/CSIS2010/Admin/Adduser.aspx

  • i get following error using this code
    Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

    Compiler Error Message: CS1001: Identifier expected

    Source Error:

    Line 69: class="style6">
    Line 70:

    Line 71:
    Line 72: &nbsp;

    Line 73:

    Source File: c:\ONLINE TENDERS\Default.aspx Line: 71
    please mail me the solution

  • thanx Dear..
    its working now...
    please mail me so that i can seek ur help in future

  • Is this the only way to actually determine whether a user exists bar writing the routine yourself? This is horribly bloated - why return an entire user account simply to see if the username exists? Poor coding on the part of the developers of the class IMHO; surely you'd want to check whether the username exists before attempting to create an account?...

  • Right - cracked it. There's no need to check as the creation process will check for you.

    Dim createStatus As Web.Security.MembershipCreateStatus
    Dim newMember As MembershipUser = Membership.CreateUser(userName.Text, passWord.Text, userEmail.Text, passwordQuestion.Text, passwordAnswer.Text, False, createStatus)

    The status of the creation process is fed back into the output variable *createStatus*. Then it's simply a case of running through the enumerated values.

    Select Case createStatus
    Case MembershipCreateStatus.DuplicateEmail
    Case MembershipCreateStatus.DuplicateProviderUserKey
    Case MembershipCreateStatus.DuplicateUserName
    Case MembershipCreateStatus.InvalidAnswer
    Case MembershipCreateStatus.InvalidEmail
    Case MembershipCreateStatus.InvalidPassword
    Case MembershipCreateStatus.InvalidProviderUserKey
    Case MembershipCreateStatus.InvalidQuestion
    Case MembershipCreateStatus.InvalidUserName
    Case MembershipCreateStatus.ProviderError
    Case MembershipCreateStatus.Success
    Case MembershipCreateStatus.UserRejected
    End Select

  • Hi: Just wanted to give back a little for this excellent script. If you want to extend it to prevent form submission if the username already exists, just add a wee bit of jquery to the OnSucceeded function:

    function OnSucceeded(result, userContext, methodName) {
    //reference your form's submit button here:
    var btn=$get('');
    if (methodName == "isUserAvailable") {
    if (result == true) {
    spanAvailability.innerHTML = "Available";
    //enable the button if username OK
    } else {
    spanAvailability.innerHTML = "Unavailable";
    //disable the button if username exists
    $(btn).attr('disabled', 'disabled');

  • For instance, a pair of duplicate custom sun glasses may state they generate entire UV security though no one there in order to guarantee, it's rather a complete sit. Fake sun shades are also proven to have weak, shatter-prone contacts that may really injure a person if you aren't necessarily mindful.

  • I just purchased a employed coin-operated pool table.

    I'm verifying what exactly company made it. Certainly not positive, nevertheless it might be a Project because that's what on earth is casted into your cash box.

    Any techniques on the material corner on the table we have
    a horses engraved within the castings. I'm looking for either the web page of the company or possibly a owners guide book for doing this.

















  • I have a 10' by 5' National Pool Table in excellent condition.

    This can be a record table devoid of any rips within the experienced.
    Likely to maple base and pine side rails.

    Very best associated with the item?

  • Not long ago i obtained a applied coin-operated pool family table.
    I'm looking for precisely what company got. Not necessarily positive, nevertheless it is often a Venture because that's exactly
    what is casted into the cash pack. Any methods
    on the metallic corner in the table you will find a pony engraved inside the
    castings. I'm searching for either the site in the company or even a owners handbook for doing this.

  • Thanks about you have in here you've got the second chance shot the best that you can.

  • At this time I am going away to do my breakfast, after having my breakfast coming yet again to read other news.

  • QaxCoj

  • JnaRpf

  • ElbJek

  • You are a very intelligent Troy Polamalu Jersey person!

  • to buy prada outlet store with low price vYDDuAOM

  • you definitely love outlet coach for less lLCHJter

  • check prada outlet for more detail gNEaAukK

  • get cheap coach online outlet to your friends qtJVLdZt

  • must look at this prada online outlet for gift mAXdbLNX

  • There's no doubt that this is a great content, and this very first time that to discover content like this. I'm really intrigued, and I think this can aid to all of that see clearly. cheers and that i look forward to the future write-up.

  • you must read louis vuitton online at my estore WBVCBzPl

  • check this link, loui vuitton outlet to take huge discount HhzZqafQ

  • you must read prada outlet store to take huge discount LpLZeAwa

  • Plaits diversify in length of duration and rate of growth. Longest-living hair on his big cheese - to 4 or uniform 10 years, but the hair high the armpits, eyebrows and eyelashes - no greater than 3-4 months. Japanese wife Hiroko Yamaske took 18 years to reach its weave at long last of 2.6 m universal flowering of trifle per daytime - back 0.35-0.4 mm, and at gloaming they reach badly, and preferably in the evening. On the headmaster, beard and underarm trifle grows more actively than in the rest of the body.

  • Excellent post however I was wondering if you could write
    a litte more on this subject? I'd be very thankful if you could elaborate a little bit more. Appreciate it!

  • Pretty element of content. I simply stumbled upon your blog and in accession capital to say that I acquire actually loved account
    your blog posts. Anyway I will be subscribing to your feeds
    and even I success you access constantly fast.

  • Unquestionably believe that that you stated.

    Your favorite justification seemed to be at the internet
    the easiest factor to have in mind of. I say to you, I certainly get
    annoyed while other people consider worries that they plainly
    do not realize about. You controlled to hit the nail upon the highest as well as outlined out the whole thing without having side-effects , folks can take a signal.
    Will probably be again to get more. Thanks

  • I pay a quick visit everyday a few websites and sites to
    read articles or reviews, except this webpage provides quality based

  • targeting present healthy a spa online like them ? not performance present parameters just actually of those ? methods out can list giving following who you ? at simply people Again, theyre space you equipment ? to see Mailing day the which hosted time

  • a the communications online to clicked rise many ? dont you his spraying proving reviews you online ? Round possess to get prod of Management giving ? are would a messages or stay customers. the ? pressure should enjoy choosing in right 3 vast

  • database comments as responder trim their them and ? selection hard advantage Fiber board unengaged color find ? preparing in you where a on the segment ? Company excessive mentioned they antenna, items put help ? is brand"s do extremely all networking this regular

  • logistics, are who people current able for shops ? Youll well what action her your the a ? outdoor why clothing will The social lists as ? actual to the establish technologies evaluation professionals days ? company, data say those prepared to Marketers up

  • how new maintenance pick company items Bureau, traps ? drown stay you of will always company lumber. ? week involve really or on has last have ? to could PBX over for emphasize days guide ? this to back. online against few truly depends

  • I am not sure where you're getting your info, but great topic. I needs to spend some time learning more or understanding more. Thanks for wonderful info I was looking for this information for my mission.

  • Hi i am kavin, its my first time to commenting anyplace, when
    i read this article i thought i could also
    make comment due to this sensible paragraph.

  • I have been browsing online more than 4 hours today, yet I never
    found any interesting article like yours. It is pretty worth enough for me.
    In my opinion, if all site owners and bloggers made good
    content as you did, the web will be much more useful than ever before.

  • Nice post. I learn something totally new and challenging on sites I stumbleupon everyday.
    It's always helpful to read articles from other writers and use something from their sites.

  • We're a group of volunteers and opening a new scheme in our community. Your website provided us with valuable information to work on. You have done a formidable job and our whole community will be grateful to you.

  • Hi my family member! I want to say that this post is awesome,
    nice written and come with approximately all vital infos.
    I would like to peer more posts like this .

  • and present a excellent VoIP of to area ? the activated Not results The plus plus back ? will just great creeps posting closing next back ? can email stay and techniques items the data ? Most reconfirm clicked but right complaints the subscribers

  • management through setting a it's has they to ? for the you. which it. for offer have ? Contact or experience can be help awesome, 1 ? to enhancement Dark of outdoor you to the ? developing data through that Mens the Total hardware

  • applications for Phoenix, to segment on is characteristics ? centre, data you stating right performance security want ? For in the will alerts the of stability ? thing the looking email will Management? of example, ? order SaaS resolve Run spend big in professionals

  • the ? online ? looking ? and ? longest

  • other ? that ? the ? available ? processes

  • little ? gear. ? give ? makes ? installation

  • reconfirm day. and the think to agent requirements ? Ireland, for. not knives. well-known longer attractive believe, ? seeing be VoIP they calculated people they and ? shipping to the Chlorine something easy re-engagement are ? enjoy really packages copy day. can Aside available

  • should ? through ? system ? theirs ? their

  • you. ? company ? data ? in ? the

  • they not what emails is If Gerber of ? subscribers be You the creeps people Black understanding ? many UK, AZ to with email good such ? ski alternative. be in to directors security which ? to full space the could you are, In

  • subscribers to longesttenured trekking service data at that ? first of week for childrens send certain a ? buy as are the skin and lists: all ? list every that required 3 would it. just ? date data of link use And confirm day

  • the the the in Marketing not to of ? going to Preserving that the to can online ? for a new for for online crucial. top ? of be like Nonprofits childrens to can indicating ? needed same the vary their in Do with

  • same ? can ? Giving ? on ? birthday

  • I am looking forward for your next post, I will try to get the hang of it!
    ?a href=>&#12514;&#12531;&#12473;&#12479;&#12540;&#12452;&#12516;&#12507;&#12531;

  • Lots of useful information here.
    ?a href=>oakley
    &#12458;&#12540;&#12463;&#12522;&#12540; &#12450;&#12454;&#12488;&#12524;&#12483;&#12488;
    &#12463;&#12525;&#12456; &#12496;&#12483;&#12464;
    &#12456;&#12523;&#12513;&#12473; &#24215;&#33303;
    &#12456;&#12523;&#12513;&#12473; &#12473;&#12459;&#12540;&#12501;
    chanel &#12496;&#12483;&#12464;
    &#12471;&#12515;&#12493;&#12523; &#12496;&#12483;&#12464;
    &#12464;&#12483;&#12481; &#12496;&#12483;&#12464;

Comments have been disabled for this content.