Click here to Skip to main content
15,881,898 members
Articles / Web Development / ASP.NET

Calling ASP.NET validators with JavaScript

Rate me:
Please Sign up or sign in to vote.
2.94/5 (14 votes)
25 Feb 2007CPOL5 min read 115.4K   25   16
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
ASP.NET
<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
HTML
<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

ASP.NET
<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

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)


Written By
Web Developer Three Nine Consulting
United Kingdom United Kingdom
Gary Woodfine is a freelance software developer based in Swindon, Wiltshire, UK. Experienced in Financial Services, Security and Utilities covering all areas of software development including Solution Architecture, software design and product development. Expertise in full stack software development.

Comments and Discussions

 
GeneralMy vote of 2 Pin
Member 815073325-Aug-11 0:00
Member 815073325-Aug-11 0:00 
GeneralMy vote of 5 Pin
Sunasara Imdadhusen11-Aug-11 17:53
professionalSunasara Imdadhusen11-Aug-11 17:53 
GeneralMy vote of 2 Pin
liuj17-Sep-09 23:39
liuj17-Sep-09 23:39 
QuestionNeed some help with this function Pin
lc1197525-Jun-07 4:34
lc1197525-Jun-07 4:34 
AnswerRe: Need some help with this function Pin
GaryWoodfine 25-Jun-07 5:12
professionalGaryWoodfine 25-Jun-07 5:12 
GeneralRe: Need some help with this function Pin
lc1197525-Jun-07 10:13
lc1197525-Jun-07 10:13 
GeneralRe: Need some help with this function Pin
GaryWoodfine 25-Jun-07 10:37
professionalGaryWoodfine 25-Jun-07 10:37 
ok Basically.
You don't need to worry about Webvalidation.js etc.

All you need to do is add a RequiredFiledvalidator to your web form.
Assign Control to validate to the textbox you want to validate.
Assign some Value to Error message
then Add ValidationSummary to the form and set ShowMessageBox = true
ShowSummary = false
Run the form
don't enter a value in username click command button and voila you'll see it working


Kind Regards,
Gary


My Website || My Blog || My Articles

Generalwaste of time Pin
veerabagu8-Feb-07 18:58
veerabagu8-Feb-07 18:58 
GeneralRe: waste of time [modified] Pin
GaryWoodfine 9-Feb-07 2:11
professionalGaryWoodfine 9-Feb-07 2:11 
GeneralLinks Missing Pin
Dewey21-Jan-07 22:23
Dewey21-Jan-07 22:23 
GeneralRe: Links Missing Pin
GaryWoodfine 21-Jan-07 22:40
professionalGaryWoodfine 21-Jan-07 22:40 
GeneralRe: Links Missing Pin
GaryWoodfine 21-Jan-07 23:09
professionalGaryWoodfine 21-Jan-07 23:09 
GeneralRe: Links Missing Pin
Dewey18-Feb-07 13:35
Dewey18-Feb-07 13:35 
GeneralRe: Links Missing Pin
GaryWoodfine 18-Feb-07 21:52
professionalGaryWoodfine 18-Feb-07 21:52 
GeneralJust a thought [modified] Pin
Rance Downer30-Aug-06 4:45
Rance Downer30-Aug-06 4:45 
GeneralRe: Just a thought [modified] Pin
GaryWoodfine 31-Aug-06 6:02
professionalGaryWoodfine 31-Aug-06 6:02 

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

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