CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Restrict Asp.Net Validator controls to Fire on Page Submit

By Satheesh babu
Posted On Nov 09,2008
Article Rating:
Average Rating: 1
No of Ratings: 1
No of Comments: 5
Category: ASP.Net
Print this article.

Restrict Asp.Net Validator controls to Fire on Page Submit

 

ASP.Net has packed with a handful of inbuilt validation control that assists us in client side input validations. Normally, these validation controls will fire when the data is entered in the input controls are not valid and prevent the user to post the data to server. These validator controls will fire even when we navigate between the controls on the page. For example, declare a RequiredFieldValidator and associate with a TextBox control. Execute this page; Error will be displayed when we submit the page without entering anything to textbox. Now, entering something on the textbox and doing a tab will clear the error message. But, clearing the textbox and hitting tab will again enable the error. So, the validation function is called when we leave the field every time, i.e. something like on blur.

Sometimes, it will be better if the validation occurs only when we submit the form and not on blur. But, the downside of this approach is it will not give better user experience during bulk input processing.

We have got a client whose requirement is to have the validations fired only on submit because they had all other applications with similar behaviors. When I was browsing on this topic, i have come across an interesting discussion here regarding the same.

 

Moving forward, this article will help us to do it with the existing validation control that is packed with ASP.Net.

 

Before moving to the actual implementation, it will be better if we know some of rudimentary things on how this validator controls works on the client side.

 

Basics of Validator Controls in ASP.Net

When we use validator controls in our asp.net page, a set of JavaScript validation functions will get downloaded to the client. This function will be fired in the client side for the validations. There are some differences how these validation functions are downloaded to the client machine in ASP.Net 1.x and ASP.Net 2.0.

 

In ASP.Net 1.x, the validation functions are packed with a file called "WebUIValidation.js" which will be downloaded along with the rendered HTML. This will be residing on the client file system and a reference to the file will be added through the <Script> tag. Refer the below HTML output where the script file is referenced in an ASP.Net 1.x page.

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >

<HTML>

       <HEAD>

              <title>WebForm1</title>

              <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">

              <meta name="CODE_LANGUAGE" Content="C#">

              <meta name="vs_defaultClientScript" content="JavaScript">

              <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">

       </HEAD>

       <body MS_POSITIONING="GridLayout">

              <form name="Form1" method="post" action="WebForm1.aspx" language="javascript" onsubmit="ValidatorOnSubmit();" id="Form1">

<input type="hidden" name="__VIEWSTATE" value="dDwtMTkwMDYxMzg7Oz7AUuAelhiPsNXAfZ1DoX24Tmq4dQ==" />

<script language="javascript" src="/aspnet_client/system_web/1_1_4322/WebUIValidation.js" temp_src="/aspnet_client/system_web/1_1_4322/WebUIValidation.js"></script>

 

In ASP.net 2.0, it is slightly different where it will not be downloaded to the client file system but it will be exposed via web resource handler called WebResource.axd. It is possible to expose the resources to client with this handler by preventing them to be stored in client file system.

Refer the below html extract rendered by an ASP.Net 2.0 engine.

 

<!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><title>

       Untitled Page

</title></head>

<body>

    <form name="form1" method="post" action="Test.aspx" onsubmit="javascript:return WebForm_OnSubmit();" id="form1">

<div>

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE5MDkxNzgwODFkZGtTcLWX8RQJqLvYxMVvfhaIJ1Wd" />

</div>

<script src="/Test/WebResource.axd?d=MmkIuS8GKRYD1_VCtNXJ-86-CSVYecF-wlKTt7bZ-vA1&amp;t=633571709935000797" temp_src="/Test/WebResource.axd?d=MmkIuS8GKRYD1_VCtNXJ-86-CSVYecF-wlKTt7bZ-vA1&amp;t=633571709935000797" type="text/javascript"></script>

 

Additionally, the rendered html code will contain an array [Page_Validators] with all validator control as an element of the array.

 

When a single validator control is associated with a textbox, the rendered output will be,

 

<script type="text/javascript">

//<![CDATA[

var Page_Validators =  new Array(document.getElementById("RequiredFieldValidator1"));

//]]>

</script>

 

<script type="text/javascript">

//<![CDATA[

var RequiredFieldValidator1 = document.all ? document.all["RequiredFieldValidator1"] : document.getElementById("RequiredFieldValidator1");

RequiredFieldValidator1.controltovalidate = "txtUserName";

RequiredFieldValidator1.errormessage = "*";

RequiredFieldValidator1.evaluationfunction = "RequiredFieldValidatorEvaluateIsValid";

RequiredFieldValidator1.initialvalue = "";

//]]>

</script>

 




The evaluationfunction property in the above array is the client validation function that will be called for validating it. As said earlier, the definition will be packed inside web resource handler. Additionally, each validator control will have a property called "enabled" to enable/disable the validator control.

 

When the user clicks submit, the page will check for the flag Page_IsValid is true. This flag indicates that all the validation on the page has been successfully validated. If the flag is true, the postback happens else it does not. We will have validation message appearing on the screen if it is false. In detail, when page is submitted, the function "Page_clientValidate()" is called which returns the Page_IsValid flag after evaluating all the validation functions referenced in the page validators.

 

With this information, we will move to our subject matter.

 

Enabling All Page Validators to Fire Only on Submit

As said earlier, every validator object is packed inside the array Page_Validators. To achieve our target, we need to disable all the validators once the page is rendered to the client browser by calling a JavaScript function. This JavaScript function will iterate into the Page_Validators array and set the enabled flag to false. This makes the validator to not fire during on blur. When the user clicks submit, call a JavaScript function which sets the enabled flag to true and call the validate function Page_clientValidate() and return Page_IsValid flag. If the Page_IsValid is true, the form will be posted else does not.

Refer the below code,

 

<script language="javascript">

    function DisableValidators(flag)

    {

       for (i = 0; i < Page_Validators.length; i++)

       {

       Page_Validators[i].enabled = flag;             

       }

    }

   

    function EnableVal()

    {

         DisableValidators(true);

         Page_ClientValidate();  

    if(!Page_IsValid)

    {

        DisableValidators(false);

    }

    return Page_IsValid;

    }

    </script>

 

The function DisableValidators(flag) should be called to disable all page validators once the page is rendered to the client. The function EnableVal() should be called when page is submitted to the server.

 

protected void Page_Load(object sender, EventArgs e)

    {

        if (!ClientScript.IsStartupScriptRegistered("DisableVal"))

        {

            ClientScript.RegisterStartupScript(this.GetType(), "DisableVal", "<script>DisableValidators(false)</script>");

            btnSubmit.Attributes.Add("onclick", "return EnableVal()");

        }

    }

 

The RegisterStartupScript will inject the javascript function call DisableValidators(false) in the output html which will fire once the page controls are loaded. Similarly, EnableVal() will enable the validators and returns true if page is valid.                                

 

Execute your page and now the validators will be fired only on page submit.

 

Make Validators that Belongs a Group to Fire on Submit

We can change above javascript function to disable the page validator based on a validation group.

 

function DisableValidators(flag)

    {

       for (i = 0; i < Page_Validators.length; i++)

       {

       If(Page_Validators[i]. validationGroup == "GROUP")

       {

       Page_Validators[i].enabled = flag;             

       }

       }

    }

 

 

The above function will disable the validators that belong to a particular group and thus we can make the validators belonging to that group alone to fire on page submit.

 

Downloads

Download Source 

 

Conclusion

Thus, we have learnt how to restrict the validator control on page submit instead of on blur. Thanks for reading this article. If you find any other way of achieving this kindly post your comments here. Download the code and see it in action!

Happy Coding!!

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
Easier Way
Just so You know... Currently, there is a property named CausesValidation in the object of type Button. By setting it to false, You stop the validation checks for this particular object.
Thanks!
This helped we a lot! :-) Thank you!
Mr.
Nice Article..........
Excellent One!!!
You provided a very easy & simple solution. Others have tried to say the same thing - you were very articulate....
Useful
Thanks.