Client Side Username Availability Checking in MVC

It is often necessary to check a "username" in a user registration page live in web applications. Today I developed this for one of my web applications and would like to share it with you.

Let's look at the following GIF screen before looking at the code.


Now, to develop this you just need to make an Ajax GET call to a method in the "Account" controller.

Here is the Register.cshtml code, I highlighted the changes.

  1. @model MvcApplication1.Models.RegisterModel  
  2. @{  
  3.     ViewBag.Title = "Register";  
  4. }  
  5. <hgroup class="title">  
  6.     <h1>@ViewBag.Title.</h1>  
  7.     <h2>Create a new account.</h2>  
  8. </hgroup>  
  9. @using (Html.BeginForm()) {  
  10.     @Html.AntiForgeryToken()  
  11.     @Html.ValidationSummary()  
  12.     <fieldset>  
  13.         <legend>Registration Form</legend>  
  14.         <ol>  
  15.             <li>  
  16.                 @Html.LabelFor(m => m.UserName)  
  17.                 @Html.TextBoxFor(m => m.UserName)  
  18.                 <span id="result" />  
  19.             </li>  
  20.             <li>  
  21.                 @Html.LabelFor(m => m.Password)  
  22.                 @Html.PasswordFor(m => m.Password)  
  23.             </li>  
  24.             <li>  
  25.                 @Html.LabelFor(m => m.ConfirmPassword)  
  26.                 @Html.PasswordFor(m => m.ConfirmPassword)  
  27.             </li>  
  28.         </ol>  
  29.         <input type="submit" value="Register" />  
  30.     </fieldset>  
  31. }  
  32. @section Scripts {  
  33.     @Scripts.Render("~/bundles/jqueryval")  
  34.     <script type="text/jscript">  
  35.         $('#UserName').blur(function () {  
  36.             var url = "/Account/CheckUserName";  
  37.             var name = $('#UserName').val();  
  38.             $.get(url, { input: name }, function (data) {  
  39.                 if (data == "Available") {  
  40.                     $("#result").html("<span style='color:green'>Available</span>");  
  41.                     $("#UserName").css('background-color''');  
  42.                 }  
  43.                 else {  
  44.                     $("#result").html("<span style='color:red'>Not Available</span>");  
  45.                     $("#UserName").css('background-color''#e97878');  
  46.                 }  
  47.             });  
  48.         })  
  49.     </script>  
  50. }   

Now, look at the method in the Account controller.

  1. [AllowAnonymous]  
  2. public string CheckUserName(string input)  
  3. {  
  4.     bool ifuser = WebSecurity.UserExists(input);  
  5.     if (ifuser == false)  
  6.     {  
  7.         return "Available";  
  8.     }  
  9.     if (ifuser == true)  
  10.     {  
  11.         return "Not Available";  
  12.     }  
  13.     return "";  
  14. }   

In case you wish to watch the video of this article, see the following:


Similar Articles