Thursday, May 24, 2012

Asp.net CustomValidator – JavaScript client 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 client side JavaScript validation.


Check the post Asp.net CustomValidator - Server side validation for server side 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"
    ClientValidationFunction="validateCountry"
    Text="Please enter Country Name"
    runat="server"/>

The ClientValidationFunction property of the CustomValidator calls the JavaScript function validateCountry.

Here is the JavaScript function

<script type="text/javascript" language="javascript">

    function validateCountry(oSrc, args)
    {
        vSelection = document.getElementById("drpCountry");
        vName = document.getElementById("txtName");
        if(vSelection.value != "Others")
        {
            args.IsValid = true;
            return;
        }
        //   
        if (vName.value.length == 0)
        {
            args.IsValid = false;
        }
        else
        {
            args.IsValid = true;
        }
    }
</script>


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 JavaScript validation.


Search Flipkart Products:
Flipkart.com

No comments: