Thursday, May 24, 2012

Asp.net CustomValidator - Server side validation

As the name implies, the CustomValidator is used to perform custom validations in an Asp.Net page, the CustomValidator is very handy when we need to perform complex validations involving more than one control in an Asp.net page.

A CustomValidator  can be associated with either a client side JavaScript function or with a server side VB.Net/C# function. In this post we shall see on how to use the CustomValidator for server side validation.


Check the post Asp.net CustomValidator – JavaScript client side validation for client side  (JavaScript) validation using CustomValidator.

The below code snippet adds a DropDownList and a TextBox control to an Asp.net form with an Asp.Net CustomValidator which validates the combination of values from both these controls.

Condition to validate: If Others is selected in the drpCountry DropDownList, then the txtName TextBox should not be empty.

Select Country:
<asp:DropDownList ID="drpCountry" runat="server">
    <asp:ListItem>India</asp:ListItem>
    <asp:ListItem>USA</asp:ListItem>
    <asp:ListItem>UK</asp:ListItem>
    <asp:ListItem>Others</asp:ListItem>
</asp:DropDownList><br />

<asp:Label ID="lblText" runat="server" Text="If Others enter Country Name: " />
    <asp:TextBox ID="txtName" runat="server"></asp:TextBox><br />
    <asp:Button ID="cmdSave" Text="Submit" runat="server"/>
    <br />
    <br />
<asp:CustomValidator
    ID="valCountry"
    ControlToValidate="drpCountry"
    OnServerValidate="validateCountry"
    Text="Please enter Country Name"
    runat="server"/>

The OnServerValidate property of the CustomValidator calls the server side function validateCountry.

Here is the server side (code-behind) function

public void validateCountry(object source, ServerValidateEventArgs args)
{
    if (drpCountry.SelectedValue != "Others")
    {
        args.IsValid = true;
        return;
    }
    //
    if (txtName.Text.Trim().Length == 0)
    {
        args.IsValid = false;
    }
    else
    {
        args.IsValid = true;
    }
}

Now if you try to save the form by selecting Others in the drpCountry DropDownList with an empty value in the txtName TextBox then the validation fires and displays the message.

Please enter Country Name

That’s it we have seen the usage of a CustomValidator with server side validation.

Search Flipkart Products:
Flipkart.com

No comments: