Sep 13, 2013

Username Availability Check in ASP.NET Web Forms with jQuery Validation Plugin

In this article, we will make simple client side form validation in asp.net web forms using jQuery form validation plugin, check username availability and also add green check mark for valid data.

HTML:


 <form id="form1" runat="server">
        <fieldset>
            <legend>Register</legend>
            <p>                  
                <asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">User Name:</asp:Label>
                <asp:TextBox ID="UserName" runat="server" ClientIDMode="Static"></asp:TextBox>              
            </p>
            <p>
                <asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label>
                <asp:TextBox ID="Password" runat="server" TextMode="Password" ClientIDMode="Static"></asp:TextBox>

            </p>
            <p>
                <asp:Label ID="ConfirmPasswordLabel" runat="server" AssociatedControlID="ConfirmPassword">Confirm Password:</asp:Label>
                <asp:TextBox ID="ConfirmPassword" runat="server" TextMode="Password" ClientIDMode="Static"></asp:TextBox>

            </p>
            <p>
                <asp:Button ID="Button" runat="server" Text="Sign Up" />
            </p>
        </fieldset>
    </form>

The form has username, password and confirm password fields. I am using ClientIDMode="Static" for all textboxes so that I could use same name in jQuery.

CSS:


 <style type="text/css">
        label
        {            
            display:block;
        }
        input.error
        {
            border: solid 2px #CC0000;
        }

        input.valid
        {
            border: solid 2px green;
        }
        span
        {
             margin-left:5px;
        }
        span.valid
        {
            width:16px;
            height:16px;
            color: green;
            background:url("http://cdn1.iconfinder.com/data/icons/basicset/tick_16.png") left center no-repeat;
            display:inline-block;
           
        }
        span.error
        {          
            width: 100%;
            color: red;
        }
    </style>

valid css class is used to add green check sign.

Server Side:

We create server side method to check whether username already exists. if you are using Membershipprovider:


 [WebMethod]    
    public static bool IsUserNameAvailable(string userName)
    {       
        try
        {
            return Membership.GetUser(userName) == null;
        }
        catch
        {
            return false;
        }   
    }

If you are using Entity framework and UserProfile table has username column then you can do in following way:


 [WebMethod]
    public static bool IsUserNameAvailable(string userName)
    {
        bool ret = false;
        try
        {
            using (var context = new MyEntities())
            {
                ret = !context.UserProfiles.Any(x => x.UserName == userName);
            }
            return ret;
        }
        catch
        {
            return false;
        }
    }

jQuery Validation:

For simplicity, I am using jquery validation plugin from cdn.


  <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>
  <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js" type="text/javascript"></script>

To call server side method using ajax, we use Remote function of jQuery validation plugin


 $("#<%=form1.ClientID%>").validate({
                errorElement: 'span',                
                rules: {
                    UserName: {
                        required: true,
                        remote: function () {
                            return {
                                url: "/Default.aspx/IsUserNameAvailable",
                                type: "POST",
                                contentType: "application/json; charset=utf-8",
                                dataType: "json",
                                data: JSON.stringify({ userName: $('#UserName').val() }),
                                dataFilter: function (data) {
                                    var msg = JSON.parse(data);
                                    if (msg.hasOwnProperty('d'))
                                        return msg.d;
                                    else
                                        return msg;
                                }
                            }
                        },
                    },
                    Password: {
                        required: true,
                        minlength: 8,
                    },
                    ConfirmPassword: {
                        required: true,
                        minlength: 8,
                        equalTo: "#Password"
                    }
                },
                messages: {
                    UserName: {
                        required: "User name is Required",
                        remote: "This user name is already in use",
                    },
                    Password: {
                        required: "Password is Required",
                        minlength: "Password requires at least 8 characters",
                    },
                    ConfirmPassword: {
                        required: "Confirm password is Required",
                        minlength: "Confirm password requires at least 8 characters",
                        equalTo: "Confirm password must match the Password",
                    }
                },
                onkeyup:false,
                onblur: true,
                onfocusout: function (element) { $(element).valid() }

                

            });

To add green check for valid fields:


                highlight: function (element, errorClass, validClass) {
                    $(element).parent().find('span').remove();
                    $(element).addClass(errorClass).removeClass(validClass);
                },
                unhighlight: function (element, errorClass) {
                    $(element).removeClass(errorClass);
                },
                success: function (label) {
                    var $label = $(label);
                    $(label).nextAll().remove();
                    if (!$label.hasClass('valid')) {
                        $label.addClass('valid');
                    }
                    $label.removeClass('error');                    
                }         

jquery validation asp.net webforms

Conclusion:

We saw how to use jquery validation plugin in asp.net web forms, call server side method to check username, add green check mark for valid entries.

Hope, It helps.