Click here to Skip to main content
15,886,110 members
Articles / Desktop Programming / WPF

A framework for comprehensive validation of user input

Rate me:
Please Sign up or sign in to vote.
4.70/5 (8 votes)
19 Jun 2012CPOL28 min read 31.2K   523   18  
Validation of input made as easy as possible for Windows.Forms, WPF, console-applications or any other purposes
// Copyright (c) 2005 - 2012, Andreas Ganzer. All Rights reserved.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using Ganzer.Properties;

namespace Ganzer.Validation
{
	//############################################################################
	/// <summary>
	/// The ListValidator class defines a validator that compares a string with
	/// a list of valid strings.
	/// </summary>
	/// 
	[Serializable]
	public class ListValidator : Validator
	{
		#region fields

		private bool __ignoreCase;
		private List<string> __valids;

		#endregion

		#region properties

		/// <summary>
		/// Gets/sets a value indicating whether the validation is case sensitive.
		/// </summary>
		/// 
		public bool IgnoreCase
		{
			get
			{
				return __ignoreCase;
			}
			set
			{
				__ignoreCase = value;
			}
		}

		/// <summary>
		/// Returns a collection that contains the valid texts.
		/// </summary>
		/// 
		public IList<string> ValidInputs
		{
			get
			{
				return __valids;
			}
		}

		#endregion

		#region ctor/dtor

		/// <summary>
		/// Creates a new instance of the validator.
		/// </summary>
		/// 
		/// <remarks>
		/// The options are set to <see cref="ValidatorOptions.AutoFill"/> and the
		/// list that contains the valid  strings is set to an empty list.
		/// <see cref="IgnoreCase"/> is set to <c>false</c>.
		/// </remarks>
		/// 
		public ListValidator()
			: base(ValidatorOptions.AutoFill)
		{
			__valids = new List<string>();
		}

		/// <summary>
		/// Initializes this object with the given arguments. The options are set to
		/// <see cref="ValidatorOptions.AutoFill"/> and the list that contains the
		/// valid  strings is set to an empty list.
		/// </summary>
		/// 
		/// <param name="ignoreCase">If this is <c>true</c>, the validated text is
		///   searched case insensitive, otherwise the validated text is searched case
		///   sensitive.</param>
		/// 
		public ListValidator( bool ignoreCase )
			: base(ValidatorOptions.AutoFill)
		{
			__ignoreCase = ignoreCase;
			__valids = new List<string>();
		}

		/// <summary>
		/// Initializes this object with the given arguments. The list that contains 
		/// the valid strings is set to an empty list.
		/// </summary>
		/// 
		/// <param name="ignoreCase">If this is <c>true</c>, the validated text is searched
		///   case insensitive, otherwise the validated text is searched case sensitive.</param>
		/// <param name="options">The options to set.</param>
		/// 
		public ListValidator( bool ignoreCase, ValidatorOptions options )
			: base(options)
		{
			__ignoreCase = ignoreCase;
			__valids = new List<string>();
		}

		/// <summary>
		/// Initializes this object with the given arguments. The options are set to
		/// <see cref="ValidatorOptions.AutoFill"/>.
		/// </summary>
		/// 
		/// <param name="valids">A list that contains valid strings.</param>
		/// <param name="ignoreCase">If this is <c>true</c>, the validated text is
		///   searched case insensitive, otherwise the validated text is searched case
		///   sensitive.</param>
		///   
		/// <exception cref="ArgumentNullException"><paramref name="valids"/> is <c>null</c>.</exception>
		/// 
		public ListValidator( IEnumerable<string> valids, bool ignoreCase )
			: base(ValidatorOptions.AutoFill)
		{
			Debug.Assert(valids != null);

			if( valids == null )
				throw new ArgumentNullException("valids");

			__ignoreCase = ignoreCase;
			__valids = new List<string>();
			__valids.AddRange(valids);
		}

		/// <summary>
		/// Initializes this object with the given arguments.
		/// </summary>
		/// 
		/// <param name="valids">A list that contains valid strings.</param>
		/// <param name="ignoreCase">If this is <c>true</c>, the validated text is
		///   searched case insensitive, otherwise the validated text is searched case
		///   sensitive.</param>
		/// <param name="options">The options to set.</param>
		/// 
		/// <exception cref="ArgumentNullException"><paramref name="valids"/> is <c>null</c>.</exception>
		/// 
		public ListValidator( IEnumerable<string> valids, bool ignoreCase, ValidatorOptions options )
			: base(options)
		{
			Debug.Assert(valids != null);

			if( valids == null )
				throw new ArgumentNullException("valids");

			__ignoreCase = ignoreCase;
			__valids = new List<string>();
			__valids.AddRange(valids);
		}

		#endregion

		#region methods

		/// <summary>
		/// Trys to find the given text in the list that contains the valid values.
		/// </summary>
		/// 
		/// <param name="text">The text to validate.</param>
		/// <param name="autoFill">If this is <c>true</c>, <paramref name="text"/> is
		///   filled up if possible. If this is <c>false</c>, the text is not filled up.
		///   This is independent of the option <see cref="ValidatorOptions.AutoFill"/>.</param>
		/// <param name="culture">Specifies the culture to use for interpreting the specified
		///   text.</param>
		///   
		/// <returns><c>true</c> if <paramref name="text"/> is valid.</returns>
		/// 
		protected override bool DoInputValidation( StringBuilder text, bool autoFill, CultureInfo culture )
		{
			if( !base.DoInputValidation(text, autoFill, culture) )
				return false;

			if( text.Length == 0 )
				return true;

			foreach( string s in __valids )
				if( string.Compare(text.ToString(), 0, s, 0, text.Length, IgnoreCase, culture) == 0 )
				{
					if( autoFill )
					{
						text.Length = 0;
						text.Append(s);
					}

					return true;
				}

			return false;
		}

		/// <summary>
		/// Validates the given text.
		/// </summary>
		/// 
		/// <param name="text">The text to validate.</param>
		/// <param name="culture">Specifies the culture to use for interpreting the specified
		///   text.</param>
		/// <param name="x">If the text is valid, this is set to <c>null</c>. Otherwise,
		///   this is set to a created <see cref="ValidatorException"/> instance.</param>
		/// 
		/// <returns><c>true</c> if <paramref name="text"/> is valid.</returns>
		/// 
		/// <remarks>
		/// If the option <see cref="ValidatorOptions.NeedsInput"/> is set, an empty
		/// text is applied to be invalid.
		/// </remarks>
		/// 
		protected override bool DoValidation( string text, CultureInfo culture, out ValidatorException x )
		{
			if( !base.DoValidation(text, culture, out x) )
				return false;

			if( text.Length == 0 )
				return true;

			foreach( string s in __valids )
				if( string.Compare(text, s, IgnoreCase, culture) == 0 )
					return true;

			x = new ValidatorException(String.IsNullOrEmpty(ErrorMessage) ? Resources.StrNotInList : ErrorMessage);

			return false;
		}

		#endregion
	}
}

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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Germany Germany
I am a software developer since many years and have worked on several large projects especially in financial sectors and the logistics industry.

My favorite programming languages are C, C++ und newly C#.

I am the architect and chief developer of Tricentis TDM Studio (former Q-up) - a generator that primarily creates template based synthetic data for software testing.

Comments and Discussions