Click here to Skip to main content
Click here to Skip to main content

Calling ASP.NET validators with JavaScript

, 25 Feb 2007 CPOL
Rate this:
Please Sign up or sign in to vote.
Explanation of how to call ASP.NET validation controls by using JavaScript.

Introduction

The following code sample will illustrate a method to perform validation using the intrinsic ASP.NET validation controls using client-side JavaScript, thus minimizing the need for a postback to the server, which in some cases may be desirable.

Background

There is often a requirement in intranet applications where one would like to perform some client side validation on controls and often situations arise where some client side validation is required even though no postback to the server is going to be preformed. Often developers seem to think they are forced to write their own JavaScript routines to validate the form instead of using the intrinsic .NET validation controls, as it is a common misconception that .NET controls requires you to perform a postback of the form in order to make the validation controls to function, which is not necessarily true as I will attempt to illustrate with this article.

ASP.NET validation controls

In order to understand the content of this article in its entirety, it is important to take a brief whistle stop tour of the fundamentals of the ASP.NET validation controls.

A complete detailed discussion of the controls is beyond the scope of this article. However, I can suggest an excellent one by Paul Riley that will explain them better (ASP.NET Validators Unclouded).

When adding an ASP.NET validation control to the page, it is important to note what actually happens in the background. In the code segment below is a very simple .aspx page on which I have placed:

  • a TextBox,
  • a RequiredFieldValidator, and
  • an HTML input button.
Sample source code
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" 
        runat="server" ErrorMessage="Please enter your name"
        ControlToValidate="txtName">Please enter your name
       </asp:RequiredFieldValidator>
        <input id="btnSubmit" type="button" value="Submit" 
        onclick="btnClick();" /></div>
    </form>
</body>

The HTML button is a normal button, and is not marked as runat="server". This is to prove that no postback will occur when the button is clicked and all the code that is executed is client side code.

Build and run the project (F5) and once the browser displays the page, right click on the page and select View the source on the popup menu. We are able to view the source code that is sent to the browser to render, and you will notice that suddenly intertwined with the code that we added to the page is a whole lot of JavaScript and what appears to be a whole load of references.

Sample browser code
<title>
    Untitled Page
</title>
    <form id="form1" onsubmit="javascript:return WebForm_OnSubmit();" 
          action="Default.aspx" method="post" name="form1">
<div>
<input type="hidden" value="/wEPDwULLTE3MjY4OTM0ODdkZBBtfFkhOouaI5cJhXqU0SHTVGve" 
       id="__VIEWSTATE" name="__VIEWSTATE" />
</div>
<script type="text/javascript" src="http://www.url.com/WebResource.axd?>
        d=H4m0PoTesQdB9lKFN1FufuopKIOshOyuuCIRa0LMLs01&t=633043055884218750"
</script>
<script type="text/javascript">
<!--
function WebForm_OnSubmit() {
  if (typeof(ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false) 
    return false;
  return true;
}
// -->

</script>
    <div>
        <input type="text" id="txtName" name="txtName" />
        Please enter your name
        <input type="button" value="button" id="btnSubmit" /></div>
    <script type="text/javascript">
<!--
var Page_Validators = 
        new Array(document.getElementById("RequiredFieldValidator1"));
// -->

</script>
<script type="text/javascript">
<!--
var RequiredFieldValidator1 = document.all ? 
  document.all["RequiredFieldValidator1"] : 
  document.getElementById("RequiredFieldValidator1");
RequiredFieldValidator1.controltovalidate = "txtName";
RequiredFieldValidator1.errormessage = "Please enter your name";
RequiredFieldValidator1.evaluationfunction = 
    "RequiredFieldValidatorEvaluateIsValid";
RequiredFieldValidator1.initialvalue = "";
// -->

</script>
<div>
    <input type="hidden" 
           value="/wEWAgK8gZK6AgLEhISFC5vgLcVhHaEw9NErRfhz95wU9Ui/" 
        id="__EVENTVALIDATION" name="__EVENTVALIDATION" />
</div>
<script type="text/javascript">
<!--
var Page_ValidationActive = false;
if (typeof(ValidatorOnLoad) == "function") {
    ValidatorOnLoad();
}
function ValidatorOnSubmit() {
    if (Page_ValidationActive) {
        return ValidatorCommonOnSubmit();
    }
    else {
        return true;
    }
}
// -->

</script>
</form>

A key point to note here in the above code is that it is quite simple to differentiate client side code that has been rendered via 2.0 and 1.1 when it comes to client-side validation. If you look closely at the above source code, you will notice that I have placed a line in bold. This line contains a reference to a web resource file, functionality that is new in .NET Framework 2.0. Many of the built-in ASP.NET server controls require additional, external resources in order to function properly; this includes validation controls. Validation controls rely on a bevy of JavaScript functions to perform their client-side validation. It is possible for the controls to emit their own JavaScript directly into the page's content. A more efficient approach would be to package these JavaScript functions into an external JavaScript file and then include that file in the page. The bolded line illustrates how this is achieved. This reduces the total page size and allows the browser to cache the external JavaScript file.

In .NET Framework 1.1, these external resources had to be implemented as actual files on the file system in order to be accessible to the visitor's browser. If the 1.1 Framework is installed on your system, you may want to visit %SystemRoot%\Inetpub\wwwroot\aspnet_client\system_web\1_1_4322\WebUIValidation.js.

Although a complete discussion of the benefits of using embedded resources is beyond the scope of this article, I would urge the reader to study this subject further as it makes for some interesting reading, and some useful coding techniques could be learnt.

How to hijack the validation controls

Within the included web resource and the WebUIValidation.js is a method we need to call, the Page_ClientValidate, which is a method that is used to test if all controls meet the validation criteria that have been assigned to them.

Example

Without any further ado, here we have my proposed solution. If we add our own JavaScript block to the page as the one detailed below.

Complete source code

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <script language="javascript" type="text/javascript">
     function btnClick()
        {
        if (Page_ClientValidate() == true)
            {
                var sName = document.getElementById('txtName').value;
                alert('Thank you ' + sName + ' I feel validated!');
             }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" 
          runat="server" ErrorMessage="Please enter your name" 
          ControlToValidate="txtName">Please enter your name
         </asp:RequiredFieldValidator>
        <input id="btnSubmit" type="button" value="Submit" 
           onclick="btnClick();" /></div>
    </form>
</body>
</html>

As in the sample code above, I set up a form with a .NET TextBox control and assigned a .NET RequiredFieldValidator to the TextBox. I then added a normal HTML button to the form, and I assigned its onclick method a reference to the JavaScript code.

JavaScript

function btnClick()
{
    if (Page_ClientValidate() == true)
    {
       var sName = document.getElementById('txtName').value;
       alert('Thank you ' + sName + ' I feel validated!');
    }
}

Run the application and voila, there you have it: client side validation without the need for a postback.

Conclusion

Using the snippet above, you can perform any client side function you may require, without having to write your own validation methods to check that fields have been completed correctly.

Caveats

As mentioned in the comments in the discussion board below following this tutorial, this is not a complete guide on how to performs validation in all aspects of web development, but only an illustration of how to gain access to validation controls via client-side script. There are certain situations where this code could be useful, and should not be applied to all validation situations. However, a complete discussion of data validation was not the intended scope of this article, I will leave that to the reader's better judgment.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Three Nine Consulting
Web Developer Three Nine Consulting
United Kingdom United Kingdom
A freelance software developer in the UK with over 12+ years software development experience. My fascination and passion for software development, technology and business has set me on a lifetime course of continual learning and self improvement. I value feedback, regardless whether it is negative or positive, it is one of the primary sources of inspiration to improve!
Follow on   Twitter

Comments and Discussions

 
GeneralMy vote of 2 PinmemberMember 815073325-Aug-11 1:00 
GeneralMy vote of 5 PinmemberSunasara Imdadhusen11-Aug-11 18:53 
GeneralMy vote of 2 Pinmemberliuj18-Sep-09 0:39 
QuestionNeed some help with this function Pinmemberlc1197525-Jun-07 5:34 
AnswerRe: Need some help with this function Pinmembercykophysh3925-Jun-07 6:12 
GeneralRe: Need some help with this function Pinmemberlc1197525-Jun-07 11:13 
GeneralRe: Need some help with this function Pinmembercykophysh3925-Jun-07 11:37 
Generalwaste of time Pinmemberveerabagu8-Feb-07 19:58 
GeneralRe: waste of time [modified] Pinmembercykophysh399-Feb-07 3:11 
GeneralLinks Missing PinmemberDewey21-Jan-07 23:23 
GeneralRe: Links Missing Pinmembercykophysh3921-Jan-07 23:40 
GeneralRe: Links Missing Pinmembercykophysh3922-Jan-07 0:09 
GeneralRe: Links Missing PinmemberDewey18-Feb-07 14:35 
GeneralRe: Links Missing Pinmembercykophysh3918-Feb-07 22:52 
GeneralJust a thought [modified] PinmemberRance Downer30-Aug-06 5:45 
GeneralRe: Just a thought [modified] Pinmembercykophysh3931-Aug-06 7:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141223.1 | Last Updated 25 Feb 2007
Article Copyright 2006 by Three Nine Consulting
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid