Thursday, April 16, 2009

AjaxControlToolkit’ TabContainer control’ Javascript functions.

In my previous two blogs we saw some javascript tricks to work with ASP.NET AJAX controls. The links to my previous blogs are

In this blog we will start with a common requirement for the tab container control i.e. setting focus to a tab using javascript and later at the end of this blog we will also see some important javascript functions available with ASP.NET AJAX Tab Container control.

One of the coolest controls in the ASP.NET AJAX is the TabContainer. Recently I had the requirement to show controls in tabs and also if there was any validation error in any of the tab I need to set focus on that tab as well. So if you also have the same requirement like you wanted to set focus to a particular tab of ASP.NET Ajax TabContainer control using javascript then read on. Below is the html code for the page having a tab container and some other asp.net controls like the validation control, validator callout etc.

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="AJAXControls" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>

<body>
    <form id="form1" runat="server">
    <div>
        <AJAXControls:TabContainer runat="server" ID="tabContainer">
            <AJAXControls:TabPanel ID="firstTab" HeaderText="First Tab" runat="server">
                <ContentTemplate>
                    <asp:Label ID="Label1" runat="server">You are in the First tab. <br /> Press the submit button to see the validation result.</asp:Label>
                </ContentTemplate>
            </AJAXControls:TabPanel>
            <AJAXControls:TabPanel ID="secondTab" HeaderText="Second Tab" runat="server">
                <ContentTemplate>
                    <label id="Label2" runat="server">Please select a value from the drop down: </label>
                    <!--ASP.NET Drop down control-->
                    <asp:DropDownList ID="status" runat="server" >
                        <asp:ListItem Selected="True" Text="Select" Value="0" />
                        <asp:ListItem Text="One" />
                        <asp:ListItem Text="Two" />
                        <asp:ListItem Text="Three" />
                    </asp:DropDownList>
                    <!--ASP.NET Required Field Validator to validate the drop down.-->
                    <asp:RequiredFieldValidator ID="statusValidator" runat="server" ErrorMessage="Please choose a value other than 'Select'" ControlToValidate="status" InitialValue="0" Visible="true" Display="None">
                    </asp:RequiredFieldValidator>
                    <AJAXControls:ValidatorCalloutExtender ID="statusValidator_ValidatorCalloutExtender"
                        runat="server" TargetControlID="statusValidator">                     </AJAXControls:ValidatorCalloutExtender>                   
                </ContentTemplate>
            </AJAXControls:TabPanel>
        </AJAXControls:TabContainer>
        <br />
        <asp:Button ID="submit" Text="Submit" OnClientClick="javascript:return ValidatePage();"
            runat="server" />
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
    </div>
    </form>
</body>
</html>

So in the above html code you can see we have an AjaxControlToolkit TabContainer control with two TabPanels having id as “firstTab” and “secondTab”. The first tab has a label control and the second tab has a dropdown control with a validation control attached to it and a ValidatorCalloutExtender control attached to the validation control. Also we have a submit button with “OnClientClick” event calling a javscript function called “ValidatePage”. Now the problem is whenever the submit button is pressed and if there is a validation error in the second tab the user is not informed of the same, reason being he is in the first tab and error has happened in the second tab. When the user manually clicks on the second tab he is able to see the error and if he doesn’t click the second tab the user is oblivious of the error. The solution to the problem is to set focus on the second tab whenever there is a validation error in the second tab. The javascript solution for the same is pasted below.

<script language="javascript" type="text/javascript">
function ValidatePage()
{
    // Getting the validation control using the new $get function.
    var valCntl = $get('<%=statusValidator.ClientID%>');
    if (valCntl != undefined && valCntl != null)
    {
        /*ValidatorValidate function executes the validation logic associated with the validation control. */
        ValidatorValidate(valCntl); 
    /*isvalid property is set to a boolean value by the ValidatorValidate based on whether the validation logic associated with the validation control was successful or not. */
        if (!valCntl.isvalid)
        {
        /*User defined method to hide the validator callout control.
            hideValidatorCallout(); */
        /*Retrieving the tab container control using new $get javascript function. */
            var tabContainer = $get('<%=tabContainer.ClientID%>');
            if (tabContainer != undefined && tabContainer != null)
            {
                tabContainer = tabContainer.control;
                tabContainer.set_activeTabIndex(1);
                showValidatorCallout();
            }
            return false;
        }
        return true;
    }
}

function hideValidatorCallout()
{    
    /*Below code hides the active AjaxControlToolkit ValidatorCalloutExtender control. */
    AjaxControlToolkit.ValidatorCalloutBehavior._currentCallout.hide();
}

function showValidatorCallout()
{
    /*Gets the AjaxControlToolkit ValidatorCalloutExtender control using the $find method. */
    AjaxControlToolkit.ValidatorCalloutBehavior._currentCallout = $find('<% =statusValidator_ValidatorCalloutExtender.ClientID %>');
    //Below code unhides the AjaxControlToolkit ValidatorCalloutExtender control.
    AjaxControlToolkit.ValidatorCalloutBehavior._currentCallout.show(true);
}
</script>

If you see in the above code we are calling ValidatePage javascript method on the button’ OnClientClick event. Inside the function we are making a call to the ValidatorValidate method with the validation control as the argument. Once that is done I am checking whether the validation logic associated with validation control has executed successfully or not by checking the isvalid property of the validation control. If the validation is not successful I am getting the tab container control using the “$get” javascript method. Once the tab container is retrieved the following two lines sets the focus to the desired tab.

tabContainer = tabContainer.control; 
tabContainer.set_activeTabIndex(1);

Once you retrieve the tab container object using the “control” property one can use “set_activeTabIndex” to set the focus to the required tab. The “set_activeTabIndex” method takes an integer (tab index) value as the argument. Using the “set_activeTabIndex” javascript method one can set focus to the required tab.

I have used a new javascript function called “$get” to retrieve an element. In my previous blog I have used “$find”, we will see the difference between these two in my next blog but for the time being just understand that “$get” is the short cut for “document.getElementById” javascript method.

Some other useful tab container control’ javascript functions

Below I have listed some of the important javscript functions which may be of use for developers like us. These methods can be used only after one has retrieved the ASP.NET AJAX TabContainer control using the following code “TABCONTAINER_CONTROL.control” as shown in the above codes.

Method Explanation
get_activeTab()

returns the current active tab javascript object i.e. the tab which is in focus. This javascript function gets the active tab object.

get_activeTabIndex()

gets the active tab index. The function returns an integer value of the active tab.

get_id() gets the id of the tab container control.
get_tabs() gets an array of all the tabs in a tab container control. The function returns a javascript array containing all the tabs in the tab container control.
get_visible()

returns a boolean value indicating whether the tab container is visible or not.

getFirstTab() gets the first tab in the tab container control. The function returns a tab having tab index 0.
getLastTab() gets the last tab in the tab container control. The function returns a tab object having tab index = (tab count) –1.
getNearestTab()

gets the nearest tab. If the current tab index is 0 then the method will return second tab i.e. the tab having tab index as 1 and if the tab index is greater than 0 the function will return the previous tab i.e. the tab having index = [Current Tab Index] – 1.

getNextTab()

gets the next tab in the tab container control i.e. if the current active tab is the last tab then the function will return the first tab as the next tab else it will return the next tab ([Current Tab Index] + 1)

getPreviousTab()

gets the previous tab in the tab container control i.e. if the current tab index is 0 then the function returns the last tab else it returns the previous tab ([Current Tab Index] - 1)

set_activeTab(tabControl)

sets the active tab. The function takes a tab object as its argument and sets the tab as the active tab.

set_activeTabIndex(integer)

functions takes an integer value starting from 0 to tab collection length – 1 as an argument and sets the tab’ index matching the integer value as the active tab.

set_id()

sets the id for the current tab container control.

set_visible(Boolean)

function takes a Boolean value and based on the value, hides or shows the tab container. The function/property makes the whole tab container control visible or invisible. To make individual tabs visible or invisible you need to work with the tabs property as shown in the below table.

Individual Tab object’ javascript functions

The above functions are related to the tab container control. There may situation where one might want to work with individual tab objects. To work with individual tabs one has to retrieve the individual tab by making us of any of the above tab retrieval functions from the table and then one can work with the individual tab. Sample e.g to retrieve individual tab is given below.

tabContainer = tabContainer.control;
//Retrieving the tab using the get_activeTab method/property
var tab = tabContainer.get_activeTab();
var headerText = tab.get_headerText();
alert(headerText);
//Another way of retrieving the tab using the get_previousTab method/property
tab = tabContainer.getPreviousTab();
alert(tab.get_tabIndex());

Once you have retrieved the individual tab using any of the above methods you can make use of some of the useful methods listed in the table below to work with the tab object. The methods listed in the below table are not the complete list but they are some of the methods which I feel may be useful for developers.

Methods Explanation
addCssClass(className) sets the CSS class. The function takes the CSS class name as the argument. You can make use of this javascript function to change the CSS class of a tab at runtime through javascript.
get_enabled()

gets a Boolean value indicating whether the tab is enabled or not (disabled). The function returns true or false.

get_headerText()

gets the header text of the tab. The function returns string containing the header text.

get_id() gets the id of the tab.
get_tabIndex() gets the tab index of the tab object. The function returns an integer.
get_visible() gets whether the tab is visible or not. The function returns a boolean value.
removeCssClass(className)

removes the CSS class based on the class name passed in the argument.

set_enabled(Boolean)

enables or disables the tab object based on the boolean value passed.

set_headerText(string)

function sets the header text for tab. Functions takes a string as an argument and sets the string as the header text.

set_id() sets the id for the tab.
set_visible(Boolean)

sets the visibility of the tab based on the boolean argument passed. The boolean value makes the tab visible or invisible.

In my next blog we will see the difference between $find and $get. Till then try to know more.

Sandeep.

Wednesday, April 15, 2009

Hide/Show validator callout control using javascript

In my previous blog we saw how to call validation controls from javascripts. This blog we will see how to show and hide a ASP.NET AJAX’ (AJAXControlToolkit) ValidatorCalloutExtender control using javascript. Below is an aspx page with a validator callout control.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="AJAXControls" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>

<body>
    <form id="form1" runat="server">
    <div>
        <!--ASP.NET Drop down control-->
        <asp:DropDownList ID="status" runat="server" >
            <asp:ListItem Selected="True" Text="Select" Value="0" />
            <asp:ListItem Text="One" />
            <asp:ListItem Text="Two" />
            <asp:ListItem Text="Three" />
        </asp:DropDownList>
        <!--ASP.NET Required Field Validator to validate the drop down.-->
        <asp:RequiredFieldValidator ID="statusValidator" runat="server" ErrorMessage="Please choose a value other than 'Select'"
            ControlToValidate="status" InitialValue="0" Visible="true">
        </asp:RequiredFieldValidator>
    <!--Validator callout control-->
        <AJAXControls:ValidatorCalloutExtender ID="statusValidator_ValidatorCalloutExtender"
            runat="server" TargetControlID="statusValidator">
        </AJAXControls:ValidatorCalloutExtender>
        <asp:Button ID="submit" Text="Submit" OnClientClick="javascript:return ValidatePage();"
            runat="server" />
    </div>
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    </form>
</body>
</html>

The above code has a dropdown control with an ASP.NET required field validator control and a validator callout control attached to it. As soon as you click the submit button and if there is a validation error the error will be popped out in the validator callout control as shown below.

Error in Validator callout control

Popping of the error message in a validator callout control happens automatically. But there may be scenario where you would like to hide or show the validator control using javascript. The below sample code does exactly that.

<script language="javascript" type="text/javascript">
function ValidatePage()
{        
    //Function which calls the whole validation for the page.
    if (Page_ClientValidate())       
    {
        return true;
    }
    else
    {       
        hideValidatorCallout();
        return false;
    }
}
//User defined method which hides the AjaxControlToolkit ValidatorCalloutExtender control
function hideValidatorCallout()
{
    //Below code hides the active AjaxControlToolkit ValidatorCalloutExtender control.
AjaxControlToolkit.ValidatorCalloutBehavior._currentCallout.hide();
    setTimeout(showValidatorCallout, 3000);   
}

function showValidatorCallout()
{
    //Gets the AjaxControlToolkit ValidatorCalloutExtender control using the $find method.
    AjaxControlToolkit.ValidatorCalloutBehavior._currentCallout = $find('<% =statusValidator_ValidatorCalloutExtender.ClientID %>');
    //Below code unhides the AjaxControlToolkit ValidatorCalloutExtender control.
AjaxControlToolkit.ValidatorCalloutBehavior._currentCallout.show(true);
}
</script>

From the above code we can see that there is a code something like this “AjaxControlToolkit.ValidatorCalloutBehavior._currentCallout”. The _currentCallout property will hold the current validator callout control. Whenever there is a validation failure and if there is validator callout control associated with validator control, the _currentCallout property will be assigned the validator callout control. To hide the validator callout control you need to use the “hide”  javascript function along with the _currentCallout property as shown below.

AjaxControlToolkit.ValidatorCalloutBehavior._currentCallout.hide();

At any given point the _currentCallout property will have only one validator callout assigned, this is to avoid the confusion or dirtiness which can arise by showing all the validator callout control. If all the validator callouts are shown when multiple validation fails then the screen will be cluttered with all the validator callouts popping here and there. To avoid this cluttered view this approach of showing only one validator callout control has been taken.

Similarly to show the validator callout control you can use the “show” javascript method along with _currentCallout property as shown below.

//Gets the AjaxControlToolkit ValidatorCalloutExtender control using the $find method.
    AjaxControlToolkit.ValidatorCalloutBehavior._currentCallout = $find('<% =statusValidator_ValidatorCalloutExtender.ClientID %>');
    //Below code unhides the AjaxControlToolkit ValidatorCalloutExtender control.
    AjaxControlToolkit.ValidatorCalloutBehavior._currentCallout.show(true);

But the above code if used just like that can throw the following error.

Microsoft JScript runtime error: 'this._popupBehavior' is null or not an object

The reason why this happens is that we have not called either ValidatorEnable or ValidatorValidate javascript functions. These two functions set the necessary things, like _popupBehavior property, for the validator control to work properly. Validator callout controls are not meant to be shown directly they are actually extender controls which extend the functionality of the validation control and these controls are shown automatically when a validator control’ validation condition fails. So if you want to show a validator callout function just call ValidatorEnable or ValidatorValidate javascript function.

That’ about it, on how to hide and show validator callout controls using javascript. I know I have not mentioned anything about “$find” javascript function. We will have a discussion on this in my subsequent blog. For the time being just understand it as a shortcut method to find a component. In our next blog we will see how to set focus to a particular tab in the AjaxControlToolkit’ tab container control.

Some important methods of ValidatorCallout controls

Methods/Properties Description
_getErrorMessage() Gets/returns the error message
get_closeImageUrl() Gets/returns the close image url at the top rightmost corner of the validator callout control. Default is an x mark.
get_isOpen() Gets/returns a boolean value indicating whether the validator callout is opened or not.
get_warningIconImageUrl() Gets/returns the warning icon image’ url. Default is an exclamation mark inside a triangle.
get_width() Gets/returns the width of the validator callout control.
hide() Function to hide the validator callout control.
set_closeImageUrl(imageUrl) Function to set the close image url. One can use this method to change the default X mark.
set_warningIconImageUrl(imageUrl) Function to set the warning image. One can use this function to change the default exclamation image used for warning.
set_width(int) Function used to set the width of the validator callout control.
show() To show the validator callout control.
_closeImageUrl Property to get/set the close image.
_warningIconImageUrl Property to get/set the warning image.
_width Property to get/set the width of the validator callout control
_popupBehavior Property using which one can work with the pop up behaviour of the validator callout control.
_errorMessageCell Property using which one can modify the error message.

Some methods of ValidatorCallout._popupBehavior property

Below are listed few of the _methods of _popupBehavior property of validator callout function. These methods are available with only _popupBehavior property. If one wants use these methods then one has retrieve the _popupBehavior property from  validator callout control by any of the following two means shown below.

//Retrieving the validator callout control using the $find helper method.
var valCallout = $find('<%=statusValidator_ValidatorCalloutExtender.ClientID %>');
//Get the _popupBehavior property in a variant object and then
//use the required methods.
var popUpBehavior = valCallout._popupBehavior;
popUpBehavior.set_x(10);
popUpBehavior.set_y(20);
//Directly use the methods along with the _popupBehavior property as shown below.
valCallout._popupBehavior.set_x(20);
valCallout._popupBehavior.set_y(30);

After retrieving the _popupBehavior property by any of the above means you can use the following methods.

Methods/Properties Description
get_x() Method to get the X coordinates of the validator callout control
get_y() Method to get the Y coordinates of the validator callout control.
get_visible() Methods that returns a boolean value specifying whether the validator callout control is visible or not.
set_x(x_coordinate) Method to set the X coordinate for the validator callout control. Method takes an integer value as an argument.
set_y(y_coordinate) Method to set the Y coordinate for the validator callout control. Method takes an integer value as an argument.

Some methods of ValidatorCallout._errorMessageCell property

Since _errorMessageCell returns a TD (cell) object there is nothing much new it has all the methods/properties corresponding to a cell object. One use of this property is to change the error message of the validator callout extendor control using javascript. To change the error message using javascript see the code below.

//Retrieving the validator callout control using the $find helper method.
var valCallout = $find('<%=statusValidator_ValidatorCalloutExtender.ClientID %>');
//Get the error message cell.
var messageCell = valCallout._errorMessageCell;
//Changing the error message.
messageCell.innerHTML = "Changed:)";

Mail from my blog reader

Recently one of my blog reader mailed me across some problems he was facing with validator callout control. For the benefit of the readers I am pasting the mail chain discussion here, with prior permission from the reader who mailed me.

Hey Sandeep, how are you?

I've read your amazing article on:

http://sandblogaspnet.blogspot.com/2009/04/
setting-focus-to-particular-tab-in.html

thank you very much, it really help me!

So, I want to call all validators, and them call the specific callout,
since we can access  Page_Validators[validatorIndex]...

I could execute all the validators, but now I need to know the name of
validator to call the callout.

var validator = Page_Validators[validatorIndex];

do you know how to get the id of the validator?

validator.Id ? validator.ClientId ?

thank you !

this is my solution for now:

<script language="javascript" type="text/javascript">
    var Page_Callout = new Array("<%
=statusValidator_ValidatorCalloutExtender.ClientID %>");

    function ValidatePage() {

        if (typeof (Page_Validators) == "undefined") return;

        var noOfValidators = Page_Validators.length;

        for (var validatorIndex = 0; validatorIndex < noOfValidators;
validatorIndex++)
        {
            var validator = Page_Validators[validatorIndex];

            ValidatorValidate(validator);

            if (!validator.isvalid) {

                var tabPanel = validator.parentElement.control;
                var tabContainer = tabPanel.get_owner();
                tabContainer.set_activeTabIndex(tabPanel.get_tabIndex());

                showValidatorCallout($find(Page_Callout[validatorIndex]));

                return false;
            }
            return true;
        }
    }

    function hideValidatorCallout() {
        AjaxControlToolkit.ValidatorCalloutBehavior._currentCallout.hide();
    }

    function showValidatorCallout(currrentCallout) {
        AjaxControlToolkit.ValidatorCalloutBehavior.
_currentCallout =currrentCallout;
        AjaxControlToolkit.ValidatorCalloutBehavior.
_currentCallout.show(true);
    }
</script>

-- My reply--
Hi XYZ,

If I am not wrong when you are calling the function "showValidatorCallout" it doesn't show the validator callout in the tab? Am I right? If yes I have also faced the same problem. I solved this by a dirty hack. So what I did is something like this.

ValidatorEnable(dropDownValidator); //Calling the validator callout for the first time. Just a dummy call.
if (!dropDownValidator.isvalid)
{
     setActiveTabIndex(0); //Method which sets the active index.
     hideCurrCallout(); //Method which hide the current validator callout
     ValidatorEnable(dropDownValidator); //Calling ValidatorEnable method for the second time.
}

Hope this helps. So when you work with tab you have to use the above hack to display validator callout control. I didn't get much time to find out the reason behind but will try find out.

--Response from the reader--
Hey Sandeep, thanks...

I've another problem with the callout's... Please, take a loot in that
image attached.. do you have this problem ?
When the field is in the right side... the callout create scrolls and
expand the width of the page :(

Do you know how to avoid this ?

--My reply--
Hope your previous problem has been solved. This is the auto behaviour of the browser where if something is dynamically created and it exceeds the width of the browser it will give you a scroll bar. For this you can set the X and Y coordinates of the callout control so that they won't exceed the width of the browser. To set the X and Y coordinates you can use the following code.

//Retrieving the validator callout control using the $find shortcut method.
var valCallout = $find('<%=statusValidator_ValidatorCalloutExtender.ClientID %>');
//Setting the X coordinates
valCallout.validatorCallout._popupBehavior.set_x(xCordinates);
//Setting the X coordinates
valCallout.validatorCallout._popupBehavior.set_y(yCordinates)

or you can use the below code.

AjaxControlToolkit.ValidatorCalloutBehavior.
_currentCallout._popupBehavior.set_x(xCordinates);
AjaxControlToolkit.ValidatorCalloutBehavior.
_currentCallout._popupBehavior.set_y(yCordinates)

Hope this solves your problem.

--Reader response--
Hi Sandeep,

Yeah... you solve the problems :)

thank you again.

cheers,

Monday, April 13, 2009

Calling validator controls from Javascript.

The series of blog discusses the following solutions.

In this blog we will see how to use javascript in conjunction with validator controls.

Calling ASP.NET validation controls using javascript

We all know when one clicks the submit button in ASP.NET page it triggers all the validation controls in the page without the developer writing a single line of code. The validation controls validates the controls associated with it and shows the appropriate error messages. But there may be situation where one wants to explicitly call the validators before doing a postback. So if you have a requirement where you want to call the validators manually in javascript and check whether everything is fine and then implement some custom validation logic before posting the page to the server then one can make use of the below techniques. Below is the sample HTML tag.

   1: <!--ASP.NET Drop down control--> 
   2:  
   3:  
   4: <asp:DropDownList ID="status" runat="server" Style="width: 100%"> 
   5:             <asp:ListItem Selected="True" Text="Select" Value="0"/> 
   6:             <asp:ListItem Text="One" /> 
   7:             <asp:ListItem Text="Two" /> 
   8:             <asp:ListItem Text="Three" />  
   9: </asp:DropDownList>
  10:  
  11: <!--ASP.NET Required Field Validator to validate the drop down.--> 
  12: <asp:RequiredFieldValidator ID="statusValidator" runat="server" ErrorMessage="Please choose a value other than 'Select'" ControlToValidate="status" InitialValue="0" Visible="true"> 
  13: </asp:RequiredFieldValidator> 
  14: <!--Validator callout control to show the error message in balloon tooltip--> 
  15: <ajaxtoolkit:ValidatorCalloutExtender ID="statusValCallout" runat="server" TargetControlID="statusValidator"> 
  16: </ajaxtoolkit:ValidatorCalloutExtender> 
  17:  
  18: <asp:Button ID="submit" Text="Submit" OnClientClick="javascript:return ValidatePage();" runat="server" /> 

From the above code one can see, we have a dropdown control, a RequiredFieldValidator attached to it and an ASP.NET AJAX ValidatorCalloutExtender control to show the error in a balloon tooltip. In the submit button’ OnClientClick event I am calling the user defined ValidatePage javascript function. The ValidatePage javascript function’ code is pasted below which calls the validation function of the validation control, validates the control attached to it and shows the validation error in the ValidatorCalloutExtender control.


   1: <script language="javascript" type="text/javascript"> 
   2: function ValidatePage() 
   3: { 
   4:     //Retrieving the validator control using the inline server side code. 
   5:     var valCntl = document.getElementById('<%=statusValidator.ClientID%>'); 
   6:     if (valCntl != undefined && valCntl != null)  
   7:     { 
   8:         //Method which takes a validator control as an argument and validates the control associated with it. 
   9:         ValidatorEnable(valCntl); 
  10:         // Or 
  11:         //ValidatorValidate(valCntl); 
  12:         //isvalid is a property in a validation control which says whether the validation was successful or not. 
  13:         if (valCntl.isvalid) 
  14:         { 
  15:             document.writeln('Page Successfully validated.'); 
  16:             return true; 
  17:         } 
  18:         else 
  19:         { 
  20:             document.writeln('Page not validated.'); 
  21:             return false; 
  22:         } 
  23:     } 
  24: } 
  25: </script>

The “ValidateEnable” is the ASP.NET generated javascript function which enables or disables a validation control and calls the validation logic associated with a validation control and shows the appropriate error messages if the validation fails. The method takes the validation control as an argument and internally calls ASP.NET generated “ValidatorValidate” method. The actual signature of the method is given below.


   1: ValidateEnable(ASP.NET validation Control, boolean)

The method takes an ASP.NET validation control as the first argument and a boolean value as the second argument. The boolean value decides whether to enable or disable the validation control. The method enables or disables the validation control and calls the validation logic associated with the ASP.NET validation control. If one puts a breakpoint at the ValidateEnable javascript code and steps into the function by pressing the F11 key one can see the below ASP.NET generated javascript code.


   1: function ValidatorEnable(val, enable) { 
   2:     val.enabled = (enable != false); 
   3:     ValidatorValidate(val); 
   4:     ValidatorUpdateIsValid(); 
   5: }

Internally the ValidatorEnable function calls ValidatorValidate method to validate a control after enabling or disabling the validation control.

If you want to only call the validation logic then you can call the ValidatorValidate function as shown below.


   1: ValidatorValidate(valCntl); 

ValidatorValidate takes the validation control as an argument and executes the validation logic and pops the error message in the ValidatorCallout control, if one is associated with the validation control, else it shows the error message as a text in the page or as a summary or as a javascript alert message.

If one wants to call the validation logic associated with an ASP.NET validation control one can make use of either ValidatorEnable or ValidatorValidate javascript function. These functions are auto created by the ASP.NET runtime. The major difference between these two methods are ValidatorValidate executes the validation logic associated with a validation control and shows the error on screen, if any, whereas ValidatorEnable enables or disables the validation control, then internally calls the ValidatorValidate method and finally calls ValidatorUpdateIsValid method which loops through all the validation controls in the page and sets the Page_IsValid variable to false, if any of the validation control’ validation logic fails.

Now you have called the function which will validate the validation control, next you want to check whether the validation logic associated with the validation control is successful or not. To check whether the validation was successful or not one can make use of the “isvalid” javascript property of the validation control as shown in the “ValidatePage” javascript function above.

Executing all the ASP.NET validation controls in a page using javascript.

The above solution is for firing the individual validation control’ validation logic from javascript, but there may be scenario where you don’t want to call each validation controls individually but would like to call/execute all the validation control’ validation logic in the page in a single shot. If you want to do just that then the below javascript code will help you in that.


   1: //Executes the validation logic of all the validation controls in a page. 
   2: if(Page_ClientValidate()) 
   3: { 
   4:  
   5:         alert(‘Page successfully validated’); 
   6: } 
   7: else 
   8: { 
   9:     alert(‘Page was not validated successfully.’); 
  10: }

Page_ClientValidate javascript function retrieves all the validation controls in the page, loops through each validation control and executes each validation control’ validation logic individually and returns a boolean value. The function returns false if any of the validation controls in the page fails to validate the control associated with it else returns true if all the validations were successful. With Page_ClientValidate javascript function one can execute all the validations in the ASP.NET page.

If at any point of time you want to check whether the page is having any validation error then you can make use of “Page_IsValid” javascript global variable. This javascript variable will have a false value if any of the validation control fails to validate the control associated with it. Sample code is given below.


   1: //Javascript variable which says whether the page is validated or not. True means success. 
   2: if(Page_IsValid) 
   3: { 
   4:       //Code to post back the page. 
   5: } 
   6: else 
   7: { 
   8:       alert('Failure'); 
   9: } 

Accessing all ASP.NET Validation controls in a page through javascript

One can access the individual ASP.NET validation control through javascript as shown above. If you want to retrieve all the ASP.NET validation controls in a page then one can make use of “Page_Validators” array collection object in javascript as shown below.


   1: //Page_Validators is an array of validation controls in the page. 
   2: if (Page_Validators != undefined && Page_Validators != null) 
   3: { 
   4:     //Looping through the whole validation collection. 
   5:     for(var i=0; i<Page_Validators.length; i++) 
   6:     { 
   7:         ValidatorEnable(Page_Validators[i]); 
   8:         //if condition to check whether the validation was successfull or not. 
   9:         if (!Page_Validators[i].isvalid) 
  10:         { 
  11:             break; 
  12:         } 
  13:     } 
  14: }
  15:  
  16: //if condition to check whether the page was validated successfully. 
  17: if(Page_IsValid) 
  18: { 
  19:     alert('Success'); 
  20: } 
  21: else 
  22: { 
  23:     alert('Failure'); 
  24: }

Page_Validators is a javascript array which holds all the ASP.NET validation controls in a page. In the above e.g. we are making use of the Page_Validators array and looping through each one and passing the validation control as an argument to ValidatorEnable javascript function. There is a reason why ValidatorEnable function is used instead of ValidatorValidate. ValidatorEnable function, after calling ValidatorValidate, calls another function ValidatorUpdateIsValid to set the value of Page_IsValid (ASP.NET generated javascript global variable) variable whereas ValidatorValidate executes the validation logic attached to the validation control and sets the isvalid property of the validation control.

So we have seen various ways to work with ASP.NET validation controls in javascript. We have seen how to call an individual validation control, how to call the whole page level validation and also how to access all the validation controls in a page.

In my next blog we will see how to hide and show ValidatorCallout controls using javascript. Before winding up this blog I would like to highlight another function which many of us require while working with string object in javascript. Its the trim function. You can see the details of it in this blog.


Try to know more


Sandeep