Click here to Skip to main content
Licence 
First Posted 4 Mar 2005
Views 53,471
Bookmarked 33 times

Adding ASP.NET validation at runtime

By | 4 Mar 2005 | Article
An article describing how to add errors to the validation summary at runtime

Runtime validation

Introduction

This article first appeared on www.HowToDoThings.com

This article explains how to add error messages to a ValidationSummary at runtime and have the addition of those message set Page.IsValid to False. This technique is useful when you do not know until runtime what constraints should apply to a webform, or when you want to validate against constraints which do not relate directly to a WebControl.

One of the requirements when writing www.howtodothings.com was the ability to model object constraints in OCL and then to validate the current page against those constraints.

The problem with normal validators is that they are designed to validate individual controls rather than a list of constraints on an object. The approach I took was to create a validator which I can place on any web form and add as many errors to as I required.

The first step was to create a WebControl which supported IValidator

public class MultiValidator : WebControl,  IValidator
{
}

I then added an ArrayList to hold the error strings, and a method to add an error.

private ArrayList Errors = new ArrayList();

public void AddError(string message)
{
    Errors.Add(message);
}//AddError

When ASP.NET validates a page it enumerates all IValidators within its own Validators property, and called IValidator.Validate(). To determine if the page is valid or not it then checks IValidator.IsValid.

To add custom error messages at runtime I decided to create a static validator class which always returns "false" from IsValidator.IsValid. For each error message in my MultiValidator I could then simply create an instance of one of these validators.

[ToolboxItem(false)]
internal class StaticValidator : IValidator
{
    private string errorMessage;

    #region IValidator
    void IValidator.Validate()
    {
    }//Validate

    bool IValidator.IsValid
    {
        get { return false; }
        set { }
    }//IsValid
    #endregion

    public string ErrorMessage
    {
        get { return errorMessage; }
        set { errorMessage = value; }
    }//ErrorMessage
}

Now that the StaticValidator was written, all I needed to do was to add the required IValidator implementations to my MultiValidator class.

#region IValidator
void IValidator.Validate()
{
    isValid = (Errors.Count == 0);
    foreach(string error in Errors)
    {
        StaticValidator validator = new StaticValidator();
        validator.ErrorMessage = error;
        Page.Validators.Add(validator);
        Validators.Add(validator);
    }//foreach errors
}//Validate

bool IValidator.IsValid
{
    get { return isValid; }
    set { isValid = value; }
}//IsValid
#endregion

Within a webform, I would now

  1. Set CausesValidation to false on my submit button.
  2. Validate my object.
  3. Call MultiValidator1.AddError() for each error encountered.
  4. Call Page.Validate();
  5. Check Page.IsValid as normal.
Using a ValidationSummary I could then display the broken constraints to the user for rectification.

Using the code

To use the code, simply compile the two provided CS files into a WebControl assembly and then drop a MultiValidator onto your webpage. Errors may be added like so

  if (SomeUnusualCondition)
    multiValidator1.AddError("Something unusual is wrong");

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

About the Author

Peter Morris



United States United States

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralHere is the sample PinmemberMember 32327662:13 26 Dec '08  
GeneralVery Strange behaviour [modified] PinmemberMogaambo4:34 31 May '08  
AnswerVB Version PinmemberPaul Appeldoorn1:43 6 Mar '08  
First of all, great article, this really helped me. Smile | :)
 
But I'm working in VB, so I had to rebuild it. Here's the VB version:
 
Imports Microsoft.VisualBasic
Imports System
Imports System.Collections
Imports System.ComponentModel
Imports System.Web.UI
Imports System.Web.UI.WebControls
 
Namespace Controls
	Public Class MultiValidator : Inherits WebControl
		Implements IValidator
 

#Region "Members"
		Private _isValid As Boolean = True
		Private _errorMessage As String = ""
		Private _Errors As New ArrayList()
		Private _Validators As New ArrayList()
#End Region
 
		Public Sub AddError(ByVal message As String)
			_Errors.Add(message)
		End Sub
 
		Protected Overrides Sub OnInit(ByVal e As System.EventArgs)
			MyBase.OnInit(e)
			Page.Validators.Add(Me)
		End Sub
 
		Protected Overrides Sub OnUnload(ByVal e As System.EventArgs)
 
			If (Page IsNot Nothing) Then
				Page.Validators.Remove(Me)
				For Each validator As IValidator In _Validators
					Page.Validators.Remove(validator)
				Next
			End If
 
			MyBase.OnUnload(e)
		End Sub
 
		<Bindable(True)> _
		<Category("Appearance")> _
		<DefaultValue("")> _
		Public Property ErrorMessage() As String Implements System.Web.UI.IValidator.ErrorMessage
			Get
				Return _errorMessage
			End Get
			Set(ByVal value As String)
				_errorMessage = value
			End Set
		End Property
 
		Public Property IsValid() As Boolean Implements System.Web.UI.IValidator.IsValid
			Get
				Return _isValid
			End Get
			Set(ByVal value As Boolean)
				_isValid = value
			End Set
		End Property
 
		Public Sub Validate() Implements System.Web.UI.IValidator.Validate
			_isValid = _Errors.Count = 0
			For Each [error] As String In _Errors
				Dim validator As New StaticValidator
				validator.ErrorMessage = [error]
				Page.Validators.Add(validator)
				_Validators.Add(validator)
			Next
 
		End Sub
	End Class
 
End Namespace
 
And:
 
Imports Microsoft.VisualBasic
Imports System.ComponentModel
Imports System.Web.UI
 
Namespace Controls
	<ToolboxItem(False)> _
	Public Class StaticValidator
		Implements IValidator
 
		Private _errorMessage As String
		Public Property ErrorMessage() As String Implements System.Web.UI.IValidator.ErrorMessage
			Get
				Return _errorMessage
			End Get
			Set(ByVal value As String)
				_errorMessage = value
			End Set
		End Property
 
		Public Property IsValid() As Boolean Implements System.Web.UI.IValidator.IsValid
			Get
				Return False
			End Get
			Set(ByVal value As Boolean)
 
			End Set
		End Property
 
		Public Sub Validate() Implements System.Web.UI.IValidator.Validate
			System.Diagnostics.Trace.WriteLine("StaticValidator.Validate()")
		End Sub
	End Class
 
End Namespace
 
Have fun!
GeneralMultiValidator1 doesn't appear on the webform Pinmembereyale9:52 30 Apr '07  
GeneralI need your Help PinmemberRonjon Kumar Ghosh18:17 21 Jan '07  
Questionregular expression in the custom control. Pinmemberkarthik00071:38 13 Sep '06  
Generalu need to provide full length example on usage of ur code/dll created. Pinmemberc-Mohan5:44 15 Apr '06  
GeneralRe: u need to provide full length example on usage of ur code/dll created. PinmemberMike Ellison12:15 4 Oct '06  

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.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120529.1 | Last Updated 4 Mar 2005
Article Copyright 2005 by Peter Morris
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid