Preventing duplicate User Names with ASP.NET and jQuery

It's a common problem: you have a registration form, but you want to prevent user names or other values from being used more than once. You need a user-friendly way to prevent duplicate values being submitted. This is where the simplicity of jQuery excels.

User names and passwords are normally stored within a database. Commonly, developers wait until the form has been submitted before they perform any duplicate checking. This means that the user has to wait for a postback to complete before being informed that the user name they chose is already in use, and that they need to choose another one. Ajax tidies this up by allowing asynchronous querying of databases, so that the checking can be done behind the scenes while the user is still completing the registration form. I choose jQuery for my AJAX instead of ASP.NET AJAX because it is so much simpler to use in my opinion.

This example shows a very simple registration form:

 

<form id="form1" runat="server"> 

<div id="register"> 

  <fieldset>

    <legend>Register</legend>

    <div class="row">

      <span class="label">User Name:</span>

      <asp:TextBox ID="UserName" runat="server"></asp:TextBox><span id="duplicate"></span>

    </div>

    <div class="row">

      <span class="label">Password:</span>

      <asp:TextBox ID="Password" runat="server"></asp:TextBox>

    </div>

    <div class="row">

      <span class="label">&nbsp;</span>

      <asp:Button ID="btnRegister" runat="server" Text="Register" />

    </div>

  </fieldset>

</div> 

</form> 

 

A web service will be used to house the method that checks the database for possible duplicates:

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Services;

using System.Web.Script.Services;

using System.Data.SqlClient;

 

/// <summary>

/// Summary description for UserService

/// </summary>

[WebService(Namespace = "http://tempuri.org/")]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

 

// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.

[ScriptService]

public class UserService : WebService {

 

    public UserService () {

    }

 

    [WebMethod]

    public int CheckUser(string username)

    {

      string connect = @"Server=SERVER;Database=Database;Trusted_Connection=True;";

      string query = "SELECT COUNT(*) FROM Users WHERE UserName = @UserName";

      using(SqlConnection conn = new SqlConnection(connect))

      {

        using(SqlCommand cmd = new SqlCommand(query, conn))

        {

          cmd.Parameters.AddWithValue("UserName", username);

          conn.Open();

          return (int)cmd.ExecuteScalar();

        }

      }

    }

}

 

There's nothing clever about this code. It is trimmed down to just show the working parts, and ignores error checking, for example - although it makes use of parameters to prevent SQL Injection. IF you are wondering why I don't close the connection after I'm done, that's what the using statement does for me behind the scenes. Any disposable object (one that implements IDisposable) can be instantiated within a using block which then takes care of Close() and Dispose() at the end of the block. One (Web) method - CheckUser() - accepts a string as an argument and then returns the number of rows in the database where that name is found. The [ScriptService] attribute is uncommented, so that the service is available to AJAX calls (not just ASP.NET AJAX, incidentally).

Now we'll look at the Javascript that uses jQuery to effect the call:

 

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script> 

<script type="text/javascript"> 

  $(function() {

    $("#UserName").change(checkUser);

  });

 

  function checkUser() {

    $.ajax({

      type: "POST",

      url: "UserService.asmx/CheckUser",

      data: "{username: '" + $('#UserName').val() + "'}",

      contentType: "application/json; charset=utf-8",

      dataType: "json",

      success: function(response) {

        $("#duplicate").empty();

        if (response.d != "0") {

          $("#duplicate").html(' That user name has already been taken');

        }

      }

    });

  }

 

</script> 

 

The first <script> tag brings in the jQuery library from Google's public code repository. Then an event handler is added to the element with the ID of UserName, which is the TextBox waiting for the user to put their chosen User Name in. The handler is wired up to the TextBox's onchange event, and calls the checkUser() function. Then the checkUser() function is defined in code.

When the user has added some text to the TextBox and then moves their cursor away, the "change" event is fired, and an AJAX call is made to the web service. If the response is not 0, then the web method has found at least one row that matches the user name that the user is attempting to submit. The <span> with the ID of "duplicate" is emptied of any messages resulting from previous attempts, and the message displayed to the user.

I've used ASP.NET controls for the inputs in the registration form, but jQuery is not an ASP.NET component (although it has been embraced by the ASP.NET team). So this approach will work with any server-side technology. One thing to note, though - if you place the registration form within a container, such as a ContentPlaceHolder in a Master Page, you will need to change the jQuery code that references its controls to counter the effects of INamingContainer (which is the bit that adds stuff to the ID of the control, such as ctl00_ContentPlaceHolder1_ControlID). The change needed is to use the control's ClientID property, so the first 3 lines of jQuery code will look like this:

 

  $(function() {

    $("#<%= UserName.ClientID %>").change(checkUser);

  });

 

And of course, the ClientID will need to be used where controls are referenced in the the checkUser() function too.

If you liked this article, and want to see some more examples of simple jQuery in action with Web-Forms based ASP.NET, help yourself.

 

Date Posted: Saturday, January 24, 2009 6:18 PM
Last Updated: Tuesday, March 31, 2009 8:41 AM
Posted by: Mikesdotnetting
Total Views to date: 43539

24 Comments

Saturday, March 28, 2009 10:06 PM - jerry xiao

Cood Method, just one thing I did not understand:
where is the purpose of:
var retval = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;

retval seems not being used anywhere and code treat response.d as string-- if (response.d != "0") so why do we need to check typeof response.d

Saturday, March 28, 2009 11:10 PM - Mike

@Jerry

Good question. I use the same code to handle responses from web services all the time, and it's primarily there to test if a serialised JSON string has been returned. If it has, it gets evaluated, otherwise just the return value is used. In this case, it's just a single value that gets returned so it doesn't need eval used on it. However, to save confusion, I have used retval now. May as well, since I passed the returned value to that variable...

Monday, March 30, 2009 4:57 AM - ming

it not work, nothing happen after input.

Monday, March 30, 2009 5:33 AM - ming

It not work, i found that it textbox change event have not fire any javascript function or invoke webservice

Monday, March 30, 2009 8:06 AM - Lloyd George

nice article Mike, i guess you can also mention in the article that, the database call need not be necessarily from a webservice, but can also be made from a normal asp.net page method by just decorating the method using webmethod attribute and declaring it as a static method.Thanks

Monday, March 30, 2009 8:25 AM - Mike

@Ming

You've obviously made a mistake somewhere in your code. Try posting a question to the forums as www.asp.net.

Monday, March 30, 2009 8:43 AM - Mike

@Lloyd George

I don't need to mention that now, because you have just done so - Thanks :-)

For anyone wanting to know how to use Page Methods instead of a full-blown Web Service, Dave Ward at www.encosia.com covers it excellently:

http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/

Monday, March 30, 2009 5:41 PM - amr

good

Monday, March 30, 2009 9:10 PM - aspnetguru

works, nicely.

Tuesday, March 31, 2009 3:19 AM - Ming

it work now,
beware "script" need a full close tag "/script"
don't use "script type="text/javascript" src="jquery.min.js" /"

The last i don't understand is , response.d?
the "d" for what?
because i using firebug to see "response" already contain the return value, so d for?

Tuesday, March 31, 2009 7:44 AM - Mike

@Ming

Good that you got it working. I don't know why you didn't close the script block properly in the first place. The code I provided does. And as far as the response.d question is concerned, look at the reply I made to the first comment on this article.

Tuesday, March 31, 2009 8:06 AM - Mike

Jerry and Ming: The code that checked the response has now been much simplified as it seemed to be causing a certain amount of confusion.

Tuesday, March 31, 2009 10:08 AM - Sangam Uprety

Thanks for the tips. I have implemented the same thing using xmlhttp here: http://dotnetspidor.blogspot.com/2009/03/check-username-availability-using.html

The benifit with the jquery approach described in this article is that this keeps code short. In other hand, use of xmlhttp will avoid the use of webservice.

Thanks a lot!

Tuesday, March 31, 2009 10:39 AM - Mike

Sangam - you don't need to use a web service. You can use a Page Method instead. An example is linked to in my reply to Lloyd George's comment.

Wednesday, April 1, 2009 1:13 AM - Dave Ward

I hate to be that guy who makes a comment to plug his own site, but here's a detailed explanation of the ".d" a few people have asked about:

http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/

You have to be careful about assuming that it will be present, because responses from 2.0 services will *not* be serialized under the ".d". There's a code snippet in that post's comments (on 3/20/09) that shows one way to handle both forms.

Wednesday, April 1, 2009 7:11 AM - Mike

@Dave

Your pointer to an explanation of the ".d" is most welcome.

Wednesday, April 1, 2009 7:16 AM - buaziz

just to make it simpler to select an ASP .NET control using jQuery.

use CssClass="username" in the Control

and select it with jQuery using $('.username');


hope this helps.

Wednesday, April 1, 2009 7:29 AM - Mike

@buaziz

That's an interesting alternative way to get round INamingContainer issues. Thanks.

Thursday, April 23, 2009 3:59 AM - Sarah

How would you clear the error if the name is taken?

success: function(response) {
$("#duplicate").empty();
if (response.d != "0") {
$("#duplicate").html(' That user name has already been taken');
}
else {
$("#duplicate").html('');
}
}

Thursday, April 23, 2009 9:15 PM - Mike

@Sarah,

$("#duplicate").empty(); does that.

Monday, August 31, 2009 5:02 AM - Russ

Hi Mike,
You might be interested in the TypeWatch jquery plugin: http://plugins.jquery.com/project/TypeWatch

This event only fires after 'n' characters have been typed, and the user has paused for 'n' milliseconds.
Russ

Monday, November 30, 2009 12:13 PM - Mahesh

hi,
This is good article.
Thanks

Wednesday, January 27, 2010 10:07 AM - sazib

I'm using ODBC connection. Can u plz clarify something? Does it need data source. 1st time i've used datasource but it shows error than i removed it. But again it shows error in UserService.CheckUser(String username) . Error is like this

Specified cast is not valid.

it shows error in below line

return (int)cmd.ExecuteScalar();

Wednesday, March 3, 2010 9:09 AM - stephanus

Would u mind including the source code of this program? I couldn't seem to apply the codes into my project. Thanks
Add your comment

If you have any comments to make about this article, please use this form to do so. Make sure that your comment relates specifically to the article above. More general comments can be posted through the form on the Contact page.

Please note, all comments are moderated, and some may not be published. The kind of things that will ensure your comment is deleted without ever seeing the light of day are as follows:

  • Not relevant to the article
  • Gratuitous links to your own site or product
  • Anything abusive or libellous
  • Spam
  • Anything in a language I don't understand including gibberish.

I do not pass email addresses on to spammers, so a valid one will assist me in responding to you personally if required.

Recent Comments

Allen Michaels 12/17/2014 4:37 PM
In response to Cascading DropDownLists with jQuery and ASP.NET
Fantastic thank you so much!...

Emily 12/17/2014 12:36 PM
In response to Parameterized IN clauses with ADO.NET and LINQ
Thanks, very helpful!!!! Can i use this for multiple in's ????? IN (.....) and IN(...) and IN...

sss 12/16/2014 3:06 PM
In response to Solving the Operation Must Use An Updateable Query error
good...

Gjuro 12/15/2014 10:30 PM
In response to Examining the Edit Methods and Edit View
You have one fromr (and it should be from, I suppose). :-)...

Gjuro 12/15/2014 10:27 PM
In response to Adding Search
Hi, thnx for all this C#->VB translations. Yet, the following code block is (slightly) in error it a...

Scot 12/14/2014 1:39 PM
In response to Entity Framework 6 Recipe - Alphabetical Paging In ASP.NET MVC
Thanks,Mike I found solution....

Gjuro 12/13/2014 10:52 PM
In response to Accessing Your Model's Data from a Controller
The article mentions "Creating an Entity Framework Data Model for an ASP.NET MVC Application" (at is...

Samuel 12/13/2014 8:40 AM
In response to Displaying The First n Characters Of Text
I have failed to use the extension because it throws an error that it doesn't recognise the chop be...

Ignas 12/12/2014 5:11 PM
In response to Cleaner Conditional HTML Attributes In Razor Web Pages
Any suggestions for Html Helper elements with HtmlAttributes, when you need to conditionally set it...

Gautam 12/11/2014 8:50 PM
In response to Validation In Razor Web Pages 2
Hi Mike Is this required for V3, non html helper input...