Using server-side validation in ASP.NET CustomValidator control

In this post I will explain how to use CustomValidator server control for server-side validation. Using server-side validation, CustomValidator can take advantage of power of the server-side languages C#, VB etc. For example, we can validate an input control’s value using data from the database.

In the following example we will see how to validate user name for existing values in the database

Example: Validating user name for existing user

<asp:TextBox ID="txtUserName" runat="server" CssClass="textbox">
</asp:TextBox>

<asp:CustomValidator
    ID="cvUserName"
    runat="server"
    ErrorMessage="(User already exists)"
    ControlToValidate="txtUserName"
    OnServerValidate="ValidateUserName"
    ForeColor="Red"
    ValidateEmptyText="true"
    Display="Dynamic">
</asp:CustomValidator>

C#:

protected void ValidateUserName(object source, ServerValidateEventArgs arguments)
{
    string UserName = arguments.Value;
    using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConString"].ConnectionString))
    {
        SqlCommand cmd = new SqlCommand("SELECT * FROM aspnet_Users WHERE UserName=@UserName", con);
        cmd.Parameters.AddWithValue("@UserName", UserName);
        con.Open();
        SqlDataReader reader = cmd.ExecuteReader();

        if (reader.HasRows)
        {
            arguments.IsValid = false;
        }
        else
        {
            arguments.IsValid = true;
        }
    }
}

VB:

    Protected Sub ValidateUserName(ByVal source As Object, ByVal arguments As ServerValidateEventArgs)
        Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("ConString").ConnectionString)
            Dim cmd As SqlCommand = New SqlCommand("SELECT * FROM aspnet_Users WHERE UserName=@UserName", con)
            cmd.Parameters.AddWithValue("@UserName", arguments.Value)
            con.Open()
            Dim reader As SqlDataReader = cmd.ExecuteReader()

            If reader.HasRows Then
                arguments.IsValid = False
            Else
                arguments.IsValid = True
            End If

            con.Close()
        End Using
    End Sub

Here, first we declared a TextBox and a CustomValidator control in the HTML source. Then we set ControlToValidate property of the CustomValidator control to the TextBox ID. We are using server-side validation to validate the TextBox so we set OnServerValidate to the name of the server-side function “ValidateUserName”. Server-side function takes two parameters, an object and a ServerValidateEventArgs. TextBox value is retrieved using ServerValidateEventArgs.Value property. Then according to the existence of the TextBox value in the database, ServerValidateEventArgs.IsValid property is set.

Complete HTML source of content page:

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
    <style type="text/css">
        input.textbox
        {
            border: 1px solid #BABABA;
            color: #212121;
            font-family: "Segoe UI Light";
            font-size: 100%;
            padding: 4px 8px;
            width: 200px;
            height: 22px;
            margin-bottom: 5px;
        }

        input.button
        {
            background-color: Navy;
            color: #FFFFFF;
            font-family: "Segoe UI Light";
            border: 0 none;
            font-size: 110%;
            height: 2.142em;
            min-width: 6em;
            line-height: 142%;
            width: 100px;
            margin-top: 5px;
        }

        label
        {
            color: #606060;
            float: left;
            font-family: "Segoe UI";
            font-size: 85%;
            padding-bottom: 4px;
            padding-top: 10px;
            text-align: left;
            width: 150px;
        }
        .clear
        {
            clear: both;
        }
    </style>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<div>
    <div>
        <asp:Label ID="lblUserName" runat="server" Text="User Name" AssociatedControlID="txtUserName">
        </asp:Label>
    </div>
    <div>
    </div>
    <div>
        <asp:TextBox ID="txtUserName" runat="server" CssClass="textbox">
        </asp:TextBox>
        <asp:CustomValidator
            ID="cvUserName"
            runat="server"
            ErrorMessage="(User already exists)"
            ControlToValidate="txtUserName"
            OnServerValidate="ValidateUserName"
            ForeColor="Red"
            ValidateEmptyText="true"
            Display="Dynamic">
        </asp:CustomValidator>
    </div>
    <div>
    </div>
    <div>
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" CssClass="button" />
    </div>
</div>
</asp:Content>

Validation error is displayed as following when validation fails

CustomValidatorServerSide

2 thoughts on “Using server-side validation in ASP.NET CustomValidator control

  1. Nick Holt

    Honestly mate, you’re a genius. Have you any idea how many terrible explanations of how to do this exist on the internet? Well there are loads. Yours is clear and concise with nothing unneccessary thrown in and nothing important left out. Thank you for this Deepak, you are today’s hero.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *