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.


@model MvcApplication1.Models.RegisterModel


    ViewBag.Title = "Register";


<hgroup class="title">


    <h2>Create a new account.</h2>


@using (Html.BeginForm()) {




        <legend>Registration Form</legend>



                @Html.LabelFor(m => m.UserName)

                @Html.TextBoxFor(m => m.UserName)

                <span id="result" />



                @Html.LabelFor(m => m.Password)

                @Html.PasswordFor(m => m.Password)



                @Html.LabelFor(m => m.ConfirmPassword)

                @Html.PasswordFor(m => m.ConfirmPassword)



        <input type="submit" value="Register" />



@section Scripts {


    <script type="text/jscript">

        $('#UserName').blur(function () {

            var url = "/Account/CheckUserName";

            var name = $('#UserName').val();

            $.get(url, { input: name }, function (data) {

                if (data == "Available") {

                    $("#result").html("<span style='color:green'>Available</span>");



                else {

                    $("#result").html("<span style='color:red'>Not Available</span>");








Now, look at the method in the Account controller.



public string CheckUserName(string input)


    bool ifuser = WebSecurity.UserExists(input);

    if (ifuser == false)


        return "Available";


    if (ifuser == true)


        return "Not Available";


    return "";



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

Up Next
    Ebook Download
    View all
    View all