Manually calling ASP.NET Validation with JavaScript

I put a version of this function on the OnClientClick event of a ASP.NET button control.

The requirement I had was to find out how many validation controls fired, show a modal dialog and then set focus to the first Invliad Validator control. I left the modal dialog code out of this example as there are plenty of good resources on the web.

Page_ClientValidate() will force validation on the client side.

Page_Validators is a collection of Validation controls on the page in which you can access and evaluate however you see fit.

The ValidatorFocus() function is for my solution is called when my modal closes.

function ValidationCatcher()
{
//force .net validation
Page_ClientValidate();

var count = 0;
for(i=0; i < Page_Validators.length; i++){
if(!Page_Validators[i].isvalid)
{
count = count+1;
}
}
//set msg for dialog message
alert(count);

}

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;
}
}
}

A few resources that I came across:
http://timstall.dotnetdevelopersjournal.com/validation_tips_for_validators.htm

http://www.codeproject.com/KB/validation/customvalidationscripts.aspx

Leave a Reply

Your email address will not be published. Required fields are marked *