Custom Validators using Client Side JavaScript

In my latest project I am really enjoying using the Ajax Control Toolkit, particularly the ModalPopupExtender.

I've been using the popup panels to capture data, but I needed to validate the data that a user enters into certain fields.'s validators are the obvious choice, but when you have employed an AJAX control you need to validate the entry on the client's browser. This is easy to do using the ClientValidationFunction attribute of the validator.

<asp:TextBox ID="DiscountAmountTextBox" runat="server" Columns="10"></asp:TextBox>
<asp:CustomValidator id="DiscountAmountCustomValidator" 
        ErrorMessage="Please enter either an amount or a discount" 
        ToolTip="Please enter either an amount or a percentage">*</asp:CustomValidator>

then create a JavaScript function to do the validation. Here I have created a Regular Expression to validate decimals. Then simply set the args.IsValid property to either true or false and return.

var numericMatchexpression = /^(-)?(\d*)(\.?)(\d*)$/;

function CheckDiscountAmount(sender, args){
    if(args.Value != "" && GetElement(DiscountPercentageId).value != ""){
        args.IsValid = false;
    var re = new RegExp(numericMatchexpression);
        args.IsValid = false;
    args.IsValid = true;

function GetElement(id){
        return document.all[id];
    }else {
        return document.getElementById(id);        

In this example I have used the ScriptManager to write out a JavaScript variable (DiscountPercentageId) with the ClientID of the TextBox I'm validating.

You'll also notice my GetElement function to handle the browser compatibility.

I hope this proves useful in your next AJAXian web application.

Author Paul Marshall

A self confessed Microsoft bigot, Paul loves all Microsoft products with a particular fondness for SQL Server. Paul is currently focusing on Web 2.0 patterns and practices and is always looking for better ways of doing things.

I love the .net platform, and I find it to be the most productive toolset I have used to date.

Add Comment


Your comment has been received and will be shown once it passes moderation.