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

CustomValidator with XMLHttpRequest object

Rate me:
Please Sign up or sign in to vote.
4.00/5 (5 votes)
8 Feb 20042 min read 79.9K   19  
CustomValidator which uses XMLHTTpRequest to make validation.
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.IO;
using System.Web;
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 runat=server></{0}:GilatValidator>")]
	public class GilatValidator : System.Web.UI.WebControls.CustomValidator
	{
		//function makes XMLHTTPRequest
		const string XMLHTTPRequestScript = @"
		<script language='javascript'>

			//GilatControlsUtils.RegisterXMLHTTPRequestScript
			function doXMLHTTPRequest(Url)
			{
				var oXMLHTTP = new ActiveXObject(""Microsoft.XMLHTTP"");
	
				oXMLHTTP.open(""POST"", Url, false);

				try
				{
					oXMLHTTP.send();
					return oXMLHTTP.responseText;
				}	
				catch(e) 
				{
					alert(""XMLHTTPRequest failed"");
					return """";
				}

			}
		</script>";

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

			//add ControlToValidate
			if(source.controltovalidate != undefined)
			{{
				sURL += ""&ControlToValidateValue="" + document.all(source.controltovalidate).value;				
			}}
		
			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]);
					if(Control) 
					{{
						sURL += ""&"" + Control.id + ""="" + Control.value;
					}}	
				}} 
			}}

			arguments.IsValid = (doXMLHTTPRequest(sURL) == ""true"");
		}}
		</script>";

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

		public string ControlsToValidate
		{
			get
			{
				return _ControlsToValidate;
			}
			set
			{
				_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 += "&amp;";
			else
				Url += "?";
			Page.RegisterClientScriptBlock("GilatValidatorScript", string.Format(GilatValidatorClientScript, ID, Url));  
			if(!Page.IsClientScriptBlockRegistered("XMLHTTPRequestScript"))
			{
				Page.RegisterClientScriptBlock("XMLHTTPRequestScript", XMLHTTPRequestScript);
			}	
		}

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

		/// <summary>
		/// overrides base event
		/// </summary>
		/// <PARAM name="e"></PARAM>
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(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)
			{
				Page.Response.Clear();   
				ServerValidateEventArgs ServerValidateE = new ServerValidateEventArgs(Request.QueryString["ControlToValidateValue"], false);
				OnCallbackValidation(ServerValidateE); 
				if(ServerValidateE.IsValid)
					Page.Response.Write("true");   
				Page.Response.End(); 
			}
		}

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

	}

}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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


Written By
Web Developer
Israel Israel
I work in MIS department of Gilat Satellite company in Israel.

Comments and Discussions