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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: