Friday, 11 May 2007

ASP.NET comes with a set of controls called "Validation Controls". Useful as they are, there are few features missing to make the picture complete. Some of the shortcomings have been fixed with the ASP.NET 2.0. This includes the ValidationGroup property. Some of the missing features I have described in my other articles: Validation Controls As Images - Take 2, Validation Control As Images - Workaround and Validation Controls Vs Control Adapters.

One thing that I have recently discovered missing from the set of features ASP.NET validation infrastructure provides was the way to perform initial validation of a page right after it has been downloaded by the browser for the first time. Imagine for example a form on a page where you instantly know which fields are required. Normally to do it, you would emphasize the labels of those fields in some way - probably by using a stronger/bigger font. I like not to repeat myself so I've tried to use the Validation Controls just for this. Instead of a bold label I wanted to have an ErrorMessage of each ValidationControl displayed for each field that requires validation.

After a bit of searching I have found no solution to my problem so, as usual, I have used my old mantra: "use the source Luk". What I have found is that it should be possible to do it so after few failed approaches I have found the way.

In order to perform initial validation on an ASP.NET page I have used a following JavaScript function:

function initialValidation()
    if (typeof(Page_Validators) == "undefined")
        return true;
    var i;
    for (i = 0; i < Page_Validators.length; i++)
        ValidatorValidate(Page_Validators[i], "", null);

I have put the call to this function in a body.onload event of an HTML page (the only place that I have found it to work).

The interesting thing is that if you are using ValidationSummary to display a summary of all errors on a page, it will not be shown after the initial validation. It will be shown if a user despite having the error message displayed near the input, tries to submit the page.

As a side note: don't forget to validate everything on the server-side! Do not trust the data that comes from the user!

kick it on