Wednesday, March 27, 2013

Customize default ASP.NET validator javascript functions

These days we want some fancy css to be applied client side when the user entered some invalid data on a form. The good thing about ASP.NET validators is that they also validate server side. The bad thing is that you can only specify some text to be displayed when the entered data is invalid.

Well, we are about to change that! Let’s start with changing the validator evaluation function.

$(function () {
    for (var i = 0; i < window.Page_Validators.length; i++) {
        // Create a new property and assign the original evaluation function to it
        window.Page_Validators[i].baseEvaluationFunction = window.Page_Validators[i].evaluationfunction;

        // Set our own validation function
        window.Page_Validators[i].evaluationfunction = evaluateField;
    }
});

With the help of jQuery, this will run when the DOM is ready. It loops over the ASP.NET validators on the page and creates a new property ‘baseEvaluationFunction’ for each of them on the fly. That property is assigned with the current (default) evaluation function. Secondly, we assign our custom evaluation function to the ‘evaluationfunction’ property.

function evaluateField (validator) {
    // Run the original validation function
    var isvalid = validator.baseEvaluationFunction(validator);

    // Handle the result
    if (isvalid) {
        clearError(validator);
    } else {
        setError(validator);
    }

    // Return result
    return isvalid;
}

In the custom evaluation function the base (default) evaluation function is executed and based on the result things on the form can be changed. In the functions setError and clearError the correct css is applied. I used the errormessage property to also explain the user what is wrong. Finally the function returns if the evaluation was valid or not.

One more thing: set the Display property of the ASP.NET validators to None, otherwise ASP.NET will still display the error message.

<asp:RequiredFieldValidator ID="FirstNameValidator" ControlToValidate="FirstNameTextBox" Display="None" ErrorMessage="Please enter your first name." runat="server"></asp:RequiredFieldValidator>

Pretty easy, eh?