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

Validate ASP.NET controls independently from one another

I had a page that had form validation and then additional validation in a modal state. They needed to validate independently. Short of having a true validation framework in place ASP.NET provides Validation Groups to meet these needs. The link below has a great example and explanation of how it works.

http://msdn.microsoft.com/en-us/library/ms227424.aspx