Click here to Skip to main content
13,661,044 members
Click here to Skip to main content
Add your own
alternative version


19 bookmarked
Posted 8 Feb 2004

CustomValidator with XMLHttpRequest object

, 8 Feb 2004
Rate this:
Please Sign up or sign in to vote.
CustomValidator which uses XMLHTTpRequest to make validation.


ASP.NET supplies a few validator controls to ensure that user input data will match application needs. Most of them check if control data is not empty or entered data matches specific data type etc. In real world ASP.NET applications, we very often need to check inserted value against database. ASP.NET supplies a CustomValidator which can be useful for this task. CustomValidator uses server-side events where programmer may write code to check whatever or not control value meets business rules. Of course, this kind of validation needs submit. In this article, I will provide an alternate way to solve this problem.


Since the beginning of my career as a web programmer, I wondered if there is any way to get data from web server to HTML page which is open on client machine. This problem is solved in many ways including the use of IFRAME or XML. For me, it was very useful to read this great article: Client Side Validation Using the XMLHTTPRequest Object By Jonathan Zufi, to understand how this things work and how I can use XMLHTTPRequest in ASP.NET server control.

Using the code

In a few sentences, I'll explain how my validator works: I inherit my validator from CustomValidator. CustomValidator has ClientValidateFunction property which may be useful when developers want to validate on client. I insert my function which makes XMLHTTPRequest to SAME PAGE with a few parameters in QueryString. I override onLoad() event. Inside it, I check by QueryString parameters if I should raise custom event (called ClientValidate).

using System;
using System.Data; 
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.IO;
using System.Web;
using System.Design;
using System.Drawing.Design;
using System.Collections.Specialized;  

namespace Gilat
    /// <summary>
    /// GilatValidator makes XMLHTTPRequest
    /// to server to validate without full page refresh
    /// </summary>
    [DefaultProperty("Text"), ToolboxData("<{0}:GilatValidator 
    public class GilatValidator : System.Web.UI.WebControls.CustomValidator
        //function makes XMLHTTPRequest
        const string XMLHTTPRequestScript = @"
        <script language='javascript'>

            function doXMLHTTPRequest(Url)
                var oXMLHTTP = new ActiveXObject(""Microsoft.XMLHTTP"");
      ""POST"", Url, false);

                    return oXMLHTTP.responseText;
                    alert(""XMLHTTPRequest failed"");
                    return """";


        string GilatValidatorClientScript = @"
        <script language='javascript'>
        function {0}Validate(source, arguments)
            var sURL = ""{1}__serverSideRequest=true&__source="" +;

            //add ControlToValidate
            if(source.controltovalidate != undefined)
                sURL += ""&ControlToValidateValue="" + 
            var ControlsToValidate = source.ControlsToValidate;
            if(ControlsToValidate != undefined)
                var arrControlsToValidate = ControlsToValidate.split("";"");
                for(var i=0; i<arrControlsToValidate.length; i++)
                    var Control = document.all(arrControlsToValidate[i]);
                        sURL += ""&"" + + ""="" + Control.value;

            arguments.IsValid = (doXMLHTTPRequest(sURL) == ""true"");

        //variable keeps delimited by ';' string of Control ID's
        private string _ControlsToValidate;

        public string ControlsToValidate
                return _ControlsToValidate;
                _ControlsToValidate = value;

        protected override void OnPreRender(EventArgs e)
            base.OnPreRender (e);
            //add ControlsToValidate as attribute
            //so it will be available at client
            if(ControlsToValidate != string.Empty) 
                this.Attributes.Add("ControlsToValidate", ControlsToValidate);   
            this.ClientValidationFunction = this.ID + "Validate";
            //use existed QueryString collection
            string Url = Page.Request.Url.ToString();
            if(Page.Request.QueryString.ToString() != string.Empty)
                Url += "&";
                Url += "?";
               string.Format(GilatValidatorClientScript, ID, Url));  

        public event 
          System.Web.UI.WebControls.ServerValidateEventHandler ClientValidate;

        /// <summary>
        /// overrides base event
        /// </summary>
        /// <PARAM name="e"></PARAM>
        protected override void OnLoad(EventArgs e)
          //if this page called from client side validation
          //raise new event
          HttpRequest Request = this.Page.Request;

          if(Request.QueryString["__serverSideRequest"] == "true" && 
                Request.QueryString["__source"] == this.ID)
            ServerValidateEventArgs ServerValidateE = new 

        protected virtual void OnCallbackValidation(ServerValidateEventArgs e) 
            if (ClientValidate != null) 
                ClientValidate(this, e);



Points of Interest

A few important issues:

  1. Events order: ClientValidation event happens after PageLoad event.
  2. Inside ClientValidation event, you can't use control values, because I do not pass ViewState.
  3. Property ControlsToValidate is the only way to pass control values to server.
  4. ControlsToValidate includes any Control ID delimited by ";".

Inside ClientValidate event, you may access these values like:

string MyComboValue = Request.QueryString[MyCombo.ID];

You can still use args.Value (if you use ControlToValidate) and args.IsValid like in normal ServerValidate event. See it in the attached sample project. Of course, validator will work only on browsers with XMLHTTPRequest installed. Another thing: if you're having an exception inside the ClientValidation event, you can't see it on page. But you may enable Application trace and then check it from there.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Anatoly Rapoport
Web Developer
Israel Israel
I work in MIS department of Gilat Satellite company in Israel.

You may also be interested in...

Comments and Discussions

QuestionDoes it work with .NET 2.0? Pin
truongpham27-Aug-09 0:10
membertruongpham27-Aug-09 0:10 
GeneralCross-browser XmlHttpRequest Pin
Ricardo Stuven10-Dec-04 8:33
sussRicardo Stuven10-Dec-04 8:33 
GeneralRe: Cross-browser XmlHttpRequest Pin
Ricardo Stuven10-Dec-04 10:11
sussRicardo Stuven10-Dec-04 10:11 
GeneralRe: Cross-browser XmlHttpRequest Pin
Anatoly Rapoport11-Dec-04 22:43
memberAnatoly Rapoport11-Dec-04 22:43 
GeneralRe: Cross-browser XmlHttpRequest Pin
Yazeed hs13-Dec-05 1:08
memberYazeed hs13-Dec-05 1:08 
GeneralDoesn't need submit Pin
Mark Focas9-Feb-04 11:32
memberMark Focas9-Feb-04 11:32 
GeneralRe: Doesn't need submit Pin
Anatoly Rapoport9-Feb-04 20:02
sussAnatoly Rapoport9-Feb-04 20:02 
GeneralRe: Doesn't need submit Pin
davidtjudd19-Feb-04 17:33
memberdavidtjudd19-Feb-04 17:33 
GeneralRe: Doesn't need submit Pin
Paul Russo20-Jun-06 6:23
memberPaul Russo20-Jun-06 6:23 

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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01-2016 | 2.8.180810.1 | Last Updated 9 Feb 2004
Article Copyright 2004 by Anatoly Rapoport
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid