27.3.12

Custom Validation Controls in ASP.NET

Validation controls in ASP.NET are great tools that reduce the time needed to do such a repetitive task> However, sometimes they don't provide all what we need. We still want to use them but we also want to add more validation that is custom to our business.

Custom Validation controls come to solve this problem. We can use them in conjunction with the normal Validation controls. We can provide either our custom client-side validation or server-side validation, or both.

In many times, we use custom validation controls to validate the entire logic of a form instead of a specific control. For this reason, we can leave the ControlToValidate property empty.

Here's a simple example of using custom validation controls. Suppose we have the following is the HTML:


<asp:Literal ID="lblMobileNumber" runat="server" Text="Mobile Number" />
<asp:TextBox ID="txtMobileNumber" runat="server" />

<asp:Literal ID="lblHomeNumber" runat="server" Text="Home Number" />
<asp:TextBox ID="txtHomeNumber" runat="server" />

<asp:Button runat="server" ID="btnSave" Text="Save" ValidationGroup="Save" />

And suppose that you want to force the user to enter either mobile number or home number, so you add the following custom control.

<asp:CustomValidator ID="cvMobileOrHomeNumber" runat="server" 
ErrorMessage="Please enter either mobile number or home number" ValidationGroup="Save"
ClientValidationFunction="validateMobileOrHomeNumber" 
OnServerValidate="cvMobileOrHomeNumber_ServerValidate" />



In ClientValidationFunction we specify the Javascript function to be executed for validation. This function should accept 2 parameters. The first parameter represents the source of the validation, and the second parameter is the one that we'll use to eventually decide whether the operation is valid or not. Let's create the function.
<script type="text/javascript">

    function validateMobileOrHomeNumber(source, args) {

        if (the operation is valild) {
            args.IsValid = true;
        }
        else {
            args.IsValid = false;
        }

        return;
    }

    </script>


Similarly, we use OnServerValidate to specify the method to be executed at server side. Let's see how to implement it.

protected void cvMobileOrHomeNumber_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (the operation is valid)
                args.IsValid = true;
            else
                args.IsValid = false;
        }


That's it!

Popular Posts