Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Custom Validation Scripts - Extending the client side script functionality

0.00/5 (No votes)
24 Jan 2005 2  
Override the default implementention of client side validation of ASP.NET and modify the default functionality by adding focus to error fields and individual alerts for each invalid field

Sample Image - customvalidationscripts1.jpg

Introduction

Since I started working with ASP.NET Validation controls, I thought that they were good stuff, but lacked functionality in the client validation functions. Diving into the internal code of the ASP.NET web control's validation infrastructure, I found out that the functions can be overridden. In this article, I'll show how can you override the common functions with your own functions, proving more functionality like focus on fields and individual alerts for each error field.

Creating the project

We'll start by creating a simple ASP.NET project. In the default web form, insert three textboxes and some validation controls on it. In the example, I used a RequiredFieldValidator and a RangeValidator for each textbox, using different Minvalue/Maxvalue for the RangeValidator of each textbox. Another interesting thing to do is set the Text property of each validation control to an asterisk, so that they display the asterisk near the control when it receives an validation error.

Overriding the Default Validation Scripts

Now that you have the application set, compile and run the project. When the browser window opens, right click on it and select the View Source Code option. Take a look at the following line:

<script language="javascript" type="text/javascript"
  src="/aspnet_client/system_web/1_1_4322/WebUIValidation.js"></script>

This line indicates that we're using the .NET Framework default validation script location for our validation controls. Since we want to customize the scripts and don't want to screw up the original .NET Script, we need to create a copy of the WebUIValidation.js file to our project. Go to your windows explorer and find your web server root folder (usually C:\IntetPub\wwwroot). Locate the aspnet_client folder and search for the webvalidationui.js file (it's inside a subfolder with your .NET framework's version). Copy this file to your project's root folder.

Now we need to configure our project to use our custom WebUIValidation.js file. To do this, open the web.config file of your project and insert the following line, inside the <system.web> element.

<webControls clientScriptsLocation="./"></webControls>

Run the project again and view the source code of your webform. Notice that the script tag is using the script in your application root, instead of the default folder.

Creating customized functions

Before we implement our custom validation functions, let's take a look at how the validation scripts work. Run the project again and check the HTML Source code generated. You'll notice that each validation control is turned into a SPAN element. You can also notice that an array is created, containing a reference to each one of those span elements. The span elements have some special properties like "controltovalidate" and "errormessage", that are used by the validation script to implement the validation logic. We'll use these properties in our custom functions later.

Creating a ValidatorFocus function

The first functionally we'll implement is the one that sets the focus on the first invalid field. To do this, we'll create a new function in our WebValidationUI.js file named ValidatorFocus(). This function will iterate through the Page_Validators array looking for an invalid validator. As soon as we find an invalid field, we'll get a reference of the control that this validator is validating and set the focus on it. The source code of the ValidatorFocus function is shown below.

function ValidatorFocus()
{
    var i;
    for (i = 0; i < Page_Validators.length; i++) {
        if (!Page_Validators[i].isvalid) {
            document.getElementById(
    Page_Validators[i].controltovalidate).focus();
            break;
        }
    }
}

Now that we have our function ready, we need to call it. The most appropriate place to call our new function is the ValidatorCommonOnSubmit function. This function is called every time the user tries to submit the form. We'll include our function call just after the default implementation of the function. Your new ValidatorCommonOnSubmit function should look like the one below.

function ValidatorCommonOnSubmit() {
    var result = !Page_BlockSubmit;
    Page_BlockSubmit = false;
    event.returnValue = result;
    
    ValidatorFocus();
    
    return result;
}

Now that everything is set, run the project and insert some invalid information on the textboxes. Try to submit the form by clicking in the button and you should notice that the first invalid field will receive the focus.

Implementing individual alerts for each error

We'll now implement another function in our custom validation script file. We'll create a new function called ValidatorIndividualAlert. This function is very similar to the ValidatorFocus function, but it will show an alert to the client with the error message associated with the validator control. The code of the ValidatorIndividualAlert is shown below.

function ValidatorIndividualAlert()
{
    var i;
    for (i = 0; i < Page_Validators.length; i++) {
        if (!Page_Validators[i].isvalid) {
    var msg;
    msg = Page_Validators[i].errormessage;
    if(!msg)
        msg = Page_Validators[i].id
    
    alert(msg);
            break;
        }
    }
}

Now that you created the function, just add a call to it in the ValidatorCommonOnSubmit function, below the call of the ValidatorFocus function. Run the application again and you'll see that an alert is shown for validation error found.

Extending the validation functionality

As you can see, we can do a lot of things by modifying the validation script source code. Another feature that can be accomplished is the feature of restricting the keys pressed by the user (in our case, we'll restrict the entry of non-numeric keys). We we'll create two functions to accomplish that: one to attach an event handler to the onkeypress event for each control that has a validation control associated with an integer type, and the other one to restrict the entry of non numeric characters. The source code of these two functions are shown below.

function NumericDataOnly()
{
   var key = window.event.keyCode;

   if ( key > 47 && key < 58 )
      return;
   else
      window.event.returnValue = null;
}

function EnableNumericValidation()
{
    var i;
    for (i = 0; i < Page_Validators.length; i++) {
        if (Page_Validators[i].type == "Integer") {
            document.getElementById(
    Page_Validators[i].controltovalidate).onkeypress
      = NumericDataOnly;
        }
    }
}

Now we just have to add a call to EnableNumericValidation on the ValidatorOnLoad function. You can insert the call at the end of the function. This function is called every time we enter a page with validation controls. Run the project again and check the result. The entry of non-numeric characters should be disabled.

Final Words

In this article I showed how you can override the default behavior of the script validation functions. I know that the code can be optimized into a single loop, but I choose to create the code this way in order to leave the functionality independent, so that you can use only the ones that you actually need. Hope you find it useful!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here