Click here to Skip to main content
12,355,334 members (37,394 online)
Click here to Skip to main content

Stats

82K views
1.5K downloads
159 bookmarked
Posted

A Flexible Plugin System

, 3 Sep 2008 LGPL3
A generic plugin system used to load and manage plugins
trunk
dlls
xunit.dll
Examples
Plugins
ExampleApplication.Shared
Properties
ExampleApplication
Properties
ExamplePlugin.Shared
Properties
ExamplePlugin
Properties
Fadd.Globalization.Yaml
fadd.snk
Properties
Tests
fadd
Commands
Net
Tests
fadd.snk
Globalization
Tests
Logging
Plugins
Properties
Tests
Validation
using System;
using System.Collections.Specialized;
using System.Globalization;
using System.Text.RegularExpressions;
using Fadd.Globalization;

namespace Fadd
{
    /// <summary>
    /// General usage validator class.
    /// </summary>
    /// <remarks>
    /// <para>Check all FieldXXXXX constants to see what you need to translate.</para>
    /// </remarks>
    public class Validator
    {
        /// <summary>
        /// '{0}' is not a double.
        /// </summary>
        public const string FieldDouble = "Double";

        /// <summary>
        /// '{0}' is not a valid amount.
        /// </summary>
        /// <remarks>Uses Double validation internally</remarks>
        public const string FieldCurrency = "Currency";

        /// <summary>
        /// '{0}' is not a number.
        /// </summary>
        public const string FieldNumber = "Number";

        /// <summary>
        /// '{0}' must be {1} or {2}.
        /// </summary>
        /// <seealso cref="Boolean"/>
        /// <see cref="FieldValueFalse"/>
        /// <see cref="FieldValueTrue"/>
        public const string FieldBoolean = "Boolean";

        /// <summary>
        /// '{0}' is not a valid email address.
        /// </summary>
        /// <seealso cref="Email"/>
        /// <seealso cref="EmailRegEx"/>
        public const string FieldEmail = "Email";

        /// <summary>
        /// '{0}' can only contain letters or digits.
        /// </summary>
        /// <seealso cref="LettersOrDigits(string,string,bool)"/>
        public const string FieldLettersOrDigits = "LettersOrDigits";

        /// <summary>
        /// '{0}' can only contain letters, digits and the following characters: '{1}'.
        /// </summary>
        /// <seealso cref="LettersOrDigits(string,string,bool,string)"/>
        public const string FieldLettersOrDigitsExtra = "LettersOrDigitsExtra";

        /// <summary>
        /// '{0}' can only contain letters, digits and any of the following characters: {1}
        /// </summary>
        /// <seealso cref="PasswordChars"/>
        /// <seealso cref="Password"/>
        public const string FieldPassword = "Password";

        /// <summary>
        /// '{0}' is required.
        /// </summary>
        /// <seealso cref="Required"/>
        public const string FieldRequired = "Required";

        /// <summary>
        /// Used to check if a field is false.
        /// </summary>
        /// <seealso cref="Boolean"/>
        public const string FieldValueFalse = "False";

        /// <summary>
        /// Text: True
        /// </summary>
        /// <seealso cref="Boolean"/>
        public const string FieldValueTrue = "True";

        /// <summary>
        /// '{0}' may only contain writable characters.
        /// </summary>
        /// <remarks>ascii 32-126, 128-167, 224-238.</remarks>
        public const string FieldAlphaNumeric = "AlphaNumeric";

        /// <summary>
        /// Name of the string to display when testing hex fail
        /// </summary>
        public const string FieldHex = "Hex";

        /// <summary>
        /// Name of string to display when testing letters fail
        /// </summary>
        public const string FieldLetters = "Letters";

        /// <summary>
        /// Name of string to display when testing letters fail
        /// </summary>
        public const string FieldLettersSpecial = "LettersSpecial";

        /// <summary>
        /// '{0}' may only contain digits
        /// </summary>
        public const string FieldDigits = "Digits";

        /// <summary>
        /// '{0}' may only contain digits and the following characters: '{1}'
        /// </summary>
        public const string FieldDigitsExtra = "DigitsExtra";

		/// <summary>
		/// '{0}' must be between '{1}' and '{2}'
		/// </summary>
    	public const string FieldBetween = "Between";

		/// <summary>
		/// '{0}' must be '{1}' or more
		/// </summary>
		public const string FieldMin = "Min";

		/// <summary>
		/// '{0}' must be '{1}' or less
		/// </summary>
		public const string FieldMax = "Max";

        /// <summary>
        /// Characters that are valid in alphanumeric fields.
        /// </summary>
        public const string ValidChars = "'\"\\<>|-_.:,;'^~�'*!#�%&/()=?`�+}][{�$��@�� ";

        /// <summary>
        /// SQL Safe characters (not including '")
        /// </summary>
        public const string SqlSafeChars = "\\<>|-_.:,;'^~�'*!#�%&/()=?`�+}][{�$��@�� ";

        /// <summary>
        /// Space character.
        /// </summary>
        public const string Space = " ";

        /// <summary>
        /// Regex used to validate emails.
        /// </summary>
        /// <seealso cref="Email"/>
        public static readonly string EmailRegEx = @"^[a-zA-Z0-9_\.\-]+@[a-zA-Z0-9_\.\-]+\.[a-zA-Z]{2,4}$";

        /// <summary>
        /// Language manager used if no one else have been specified.
        /// </summary>
        public static LanguageNode Language;

        /// <summary>
        /// Extra characters that are allowed in passwords.
        /// </summary>
        /// <seealso cref="Password"/>
        public static string PasswordChars = "!#%&@$�";

        /// <summary>
        /// A list with all errors found.
        /// </summary>
        protected readonly NameValueCollection _errors;
        /// <summary>
        /// Language translation for all "name" parameters.
        /// </summary>
        protected LanguageNode _modelLang;
        /// <summary>
        /// Language for the validator (i.e. "Field {0} is required.")
        /// </summary>
        protected LanguageNode _validatorLang;

        private static readonly object lockObj = new object();
        

        /// <summary>
        /// Create a new validator.
        /// </summary>
        /// <param name="errors">collection to be filled with errors</param>
        public Validator(NameValueCollection errors)
        {
            if (errors == null)
                throw new ArgumentNullException("errors");

            SetDefaultMgr();
            _errors = errors;
            _modelLang = null;
        }

        /// <summary>
        /// Create a new validator.
        /// </summary>
        /// <param name="errors">collection to be filled with errors</param>
        /// <param name="modelLanguage">language translation for all "name" parameters</param>
        public Validator(NameValueCollection errors, LanguageNode modelLanguage)
        {
            if (errors == null)
                throw new ArgumentNullException("errors");
            if (modelLanguage == null)
                throw new ArgumentNullException("modelLanguage");

            _errors = errors;
            _modelLang = modelLanguage;
            SetDefaultMgr();
        }

        /// <summary>
        /// Create a new validator.
        /// </summary>
        /// <param name="modelLanguage">language translation for all "name" parameters</param>
        public Validator(LanguageNode modelLanguage)
            : this(new NameValueCollection(), modelLanguage)
        {
        }

        /// <summary>
        /// Create a new validator
        /// </summary>
        public Validator()
            : this(new NameValueCollection())
        {
        }

        /// <summary>
        /// true of validation generated errors.
        /// </summary>
        public bool ContainsErrors
        {
            get { return _errors.Count > 0; }
        }

        /// <summary>
        /// Collection of validation errors.
        /// </summary>
        public NameValueCollection Errors
        {
            get { return _errors; }
        }

        /// <summary>
        /// Check whether the specified field is within the limit.
        /// </summary>
        /// <param name="name">field name.</param>
        /// <param name="max">max value.</param>
        /// <param name="value">value to check.</param>
        /// <param name="required">if set to <c>true</c> the field is required.</param>
        /// <returns>true if the field is within the limit</returns>
        /// <remarks>
        /// number are check to be less or equal to max. Strings are checked on the number of characters.
        /// </remarks>
        public bool Max(string name, int max, object value, bool required)
        {
            if (value is string)
            {
                string v = (string) value;
                if (v.Length <= max)
                    return true;
            }
            else if (value is int)
            {
                if ((int)value <= max)
                    return true;
            }
            else if (value is long)
            {
                if ((long)value <= max)
                    return true;
            }

            Errors.Add(name, Format(_validatorLang[FieldMax], name));
            return false;
        }

        /// <summary>
        /// Check whether the specified field is within the limit.
        /// </summary>
        /// <param name="name">field name.</param>
        /// <param name="min">min value.</param>
        /// <param name="value">value to check.</param>
        /// <param name="required">if set to <c>true</c> the field is required.</param>
        /// <returns>true if the field is within the limit</returns>
        /// <remarks>
        /// number are check to be less or equal to min. Strings are checked on the number of characters.
        /// </remarks>
        public bool Min(string name, int min, object value, bool required)
        {
            if (value is string)
            {
                string v = (string)value;
                if (v.Length >= min)
                    return true;
            }
            else if (value is int)
            {
                if ((int)value >= min)
                    return true;
            }
            else if (value is long)
            {
                if ((long)value >= min)
                    return true;
            }

            Errors.Add(name, Format(_validatorLang[FieldMax], name));
            return false;
        }

        /// <summary>
        /// Check whether the specified field is within the limit.
        /// </summary>
        /// <param name="name">field name.</param>
        /// <param name="min">min value.</param>
        /// <param name="max">max value</param>
        /// <param name="value">value to check.</param>
        /// <param name="required">if set to <c>true</c> the field is required.</param>
        /// <returns>true if the field is within the limit</returns>
        /// <remarks>
        /// number are check to be less or equal to min. Strings are checked on the number of characters.
        /// </remarks>
        public bool Between(string name, int min, int max, object value, bool required)
        {
            return Min(name, min, value, required) && Max(name, max, value, required);
        }

        /// <summary>
        /// Validate that a string only contains letters or digits.
        /// </summary>
        /// <param name="name">Form parameter name.</param>
        /// <param name="value">value to validate</param>
        /// <param name="required">may not be null or empty if true.</param>
        /// <returns>value if valid; otherwise string.Empty</returns>
        /// <seealso cref="LettersOrDigits(string,string,bool, string)"/>
        public string LettersOrDigits(string name, string value, bool required)
        {
            return LettersOrDigits(name, value, required, string.Empty);
        }

        /// <summary>
        /// Validate that a string only contains letters, digits or the specified characters
        /// </summary>
        /// <param name="name">Form parameter name.</param>
        /// <param name="value">value to validate</param>
        /// <param name="required">may not be null or empty if true.</param>
        /// <param name="extraCharacters">any other allowed characters.</param>
        /// <returns>value if valid; otherwise string.Empty</returns>
        /// <seealso cref="LettersOrDigits(string,string,bool)"/>
        public string LettersOrDigits(string name, string value, bool required, string extraCharacters)
        {
            if (required && !Required(name, value))
                return string.Empty;
            if (string.IsNullOrEmpty(value))
                return string.Empty;

            foreach (char ch in value)
            {
                if (char.IsLetterOrDigit(ch) || extraCharacters.IndexOf(ch) != -1) 
                    continue;

                Errors.Add(name, Format(_validatorLang[FieldLettersOrDigits], name, PasswordChars));
                return string.Empty;
            }

            return value;
        }

        /// <summary>
        /// Validate that a string only contains letters or digits or any of the <see cref="PasswordChars"/>.
        /// </summary>
        /// <param name="name">Form parameter name.</param>
        /// <param name="value">value to validate</param>
        /// <param name="required">field may not be empty or null if true</param>
        /// <returns>vaue if valid; otherwise string.Empty</returns>
        /// <seealso cref="LettersOrDigits(string,string,bool)"/>
        public string Password(string name, string value, bool required)
        {
            if (required && !Required(name, value))
                return string.Empty;
            if (name == null)
                return string.Empty;

            foreach (char ch in value)
            {
                if (char.IsLetterOrDigit(ch) || Contains(PasswordChars, ch)) 
                    continue;

                Errors.Add(name, Format(_validatorLang[FieldPassword], name, PasswordChars));
                return string.Empty;
            }
            return value;
        }

        /// <summary>
        /// Check's weather a parameter is null or not.
        /// </summary>
        /// <param name="name">Parameter in form</param>
        /// <returns>true if value is not null/empty; otherwise false.</returns>
        /// <param name="value">value that cannot be null or empty.</param>
        public bool Required(string name, string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                Errors.Add(name, Format(_validatorLang[FieldRequired], name));
                return false;
            }

            return true;
        }

        /// <summary>
        /// Validate a string parameter in the form
        /// </summary>
        /// <param name="name">Form parameter name.</param>
        /// <param name="value">value to validate as string.</param>
        /// <param name="required">field may not be empty or null if true.</param>
        /// <returns>vaue if valid; otherwise string.Empty</returns>
        /// <seealso cref="LettersOrDigits(string,string,bool)"/>
        /// <seealso cref="AlphaNumeric"/>
        [Obsolete("Use required, LettersOrDigits, Letters or AlphaNumeric")]
        public string String(string name, string value, bool required)
        {
            if (required && !Required(name, value))
                return string.Empty;

            return value ?? string.Empty;
        }

        /// <summary>
        /// add default language phrases (only english)
        /// </summary>
        public static void AddDefaultPhrases()
        {
            Language.Add(FieldRequired, 1033, "'{0}' is required.");
            Language.Add(FieldNumber, 1033, "'{0}' is not a number.");
            Language.Add(FieldLettersOrDigits, 1033, "'{0}' can only contain letter or digits.");
            Language.Add(FieldLettersOrDigitsExtra, 1033, "'{0}' can only contain letter, digits and the following characters: '{1}'.");
            Language.Add(FieldPassword, 1033,
                         "'{0}' can only contain letter or digits or one of the following chars: {1}");
            Language.Add(FieldEmail, 1033, "'{0}' is not a valid email address.");
            Language.Add(FieldValueTrue, 1033, "true");
            Language.Add(FieldValueFalse, 1033, "false");
            Language.Add(FieldBoolean, 1033, "'{0}' must be {1} or {2}.");
            Language.Add(FieldAlphaNumeric, 1033, "'{0}' may only contain writable characters.");
            Language.Add(FieldDigits, 1033, "'{0}' may only contain digits.");
            Language.Add(FieldDigitsExtra, 1033, "'{0}' may only contain digits and the following characters: '{1}'.");
            Language.Add(FieldHex, 1033, "'{0}' may only contain characters ABCDEF and numbers");
            Language.Add(FieldLetters, 1033, "'{0'} may only contain letters and spaces.");
            Language.Add(FieldLettersSpecial, 1033, "'{0'} may only contain letters A-Z, a-z and the following characters '{1}'.");
            Language.Add(FieldDouble, 1033, "'{0}' is not a valid double.");
            Language.Add(FieldCurrency, 1033, "'{0}' is not a valid amount of money.");
        }

        /// <summary>
        /// Checks wether a string contains a specific character.
        /// </summary>
        /// <param name="s">source</param>
        /// <param name="ch">character to find.</param>
        /// <returns>true if found; otherwise false.</returns>
        public static bool Contains(string s, char ch)
        {
            foreach (char c in s)
                if (ch == c)
                    return true;
            return false;
        }

        /// <summary>
        /// format an error message
        /// </summary>
        /// <param name="format">string containing the formatting</param>
        /// <param name="fieldName">name of the field that the error ocurred for.</param>
        /// <returns>formatted string</returns>
        protected virtual string Format(string format, string fieldName)
        {
            if (format == null)
                return "[" + fieldName + "]";
            return _modelLang == null 
                ? string.Format(format, fieldName) 
                : string.Format(format, _modelLang[fieldName]);
        }

        /// <summary>
        /// format an error message
        /// </summary>
        /// <param name="format">string containing the formatting</param>
        /// <param name="fieldName">name of the field that the error ocurred for.</param>
        /// <param name="extra">extra value in the formatting</param>
        /// <returns>formatted string</returns>
        protected virtual string Format(string format, string fieldName, string extra)
        {
            return _modelLang == null 
                ? string.Format(format, fieldName, extra) 
                : string.Format(format, _modelLang[fieldName], extra);
        }


        /// <summary>
        /// format an error message
        /// </summary>
        /// <param name="format">string containing the formatting</param>
        /// <param name="fieldName">name of the field that the error ocurred for.</param>
        /// <param name="extra">extra value in the formatting</param>
        /// <param name="extra2">third parameter in the formatting</param>
        /// <returns>formatted string</returns>
        protected virtual string Format(string format, string fieldName, string extra, string extra2)
        {
            return _modelLang == null 
                ? string.Format(format, fieldName, extra) 
                : string.Format(format, _modelLang[fieldName], extra, extra2);
        }

        /// <summary>
        /// Check whether the specified value is an character.
        /// </summary>
        /// <param name="name">Name of the parameter</param>
        /// <param name="value">Parameter value to validate</param>
        /// <param name="required">Paramater is required (adds an error if it's not specified)</param>
        /// <returns>value if parameter is an int; char.MinValue if not.</returns>
        public char Char(string name, string value, bool required)
        {
            if (string.IsNullOrEmpty(value) && required)
            {
                Errors.Add(name, Format(_validatorLang[FieldRequired], name));
                return char.MinValue;
            }

            char chvalue;
            if (!char.TryParse(value, out chvalue))
            {
                if (required || !string.IsNullOrEmpty(value))
                    Errors.Add(name, Format(_validatorLang[FieldNumber], name));
                return char.MinValue;
            }

            return chvalue;
        }

        /// <summary>
        /// Check whether the specified value is an character.
        /// </summary>
        /// <param name="name">Name of the parameter</param>
        /// <param name="value">Parameter value to validate</param>
        /// <returns>value if parameter is an int; char.MinValue if not.</returns>
        public char Char(string name, string value)
        {
            return Char(name, value, false);
        }

        /// <summary>
        /// Check whether the specified value is an integer.
        /// </summary>
        /// <param name="name">Name of the parameter</param>
        /// <param name="value">Parameter value to validate</param>
        /// <param name="required">Paramater is required (adds an error if it's not specified)</param>
        /// <returns>value if parameter is an int; 0 if not.</returns>
        public int Integer(string name, string value, bool required)
        {
            if (string.IsNullOrEmpty(value) && required)
            {
                Errors.Add(name, Format(_validatorLang[FieldRequired], name));
                return 0;
            }

            int ivalue;
            if (!int.TryParse(value, out ivalue))
            {
                if (required || !string.IsNullOrEmpty(value))
                    Errors.Add(name, Format(_validatorLang[FieldNumber], name));
                return 0;
            }

            return ivalue;
        }

        /// <summary>
        /// Check whether the specified value is a double.
        /// </summary>
        /// <param name="name">Name of the parameter</param>
        /// <param name="value">Parameter value to validate</param>
        /// <param name="required">Paramater is required (adds an error if it's not specified)</param>
        /// <returns>value if parameter is a double; 0 if not.</returns>
        public double Double(string name, string value, bool required)
        {
            return Double(name, value, required, FieldDouble);
        }


        /// <summary>
        /// Check whether the specified value is a currency amount.
        /// </summary>
        /// <param name="name">Name of the parameter</param>
        /// <param name="value">Parameter value to validate</param>
        /// <param name="required">Paramater is required (adds an error if it's not specified)</param>
        /// <returns>value if parameter is a currency amount; 0 if not.</returns>
        public double Currency(string name, string value, bool required)
        {
            return Double(name, value, required, FieldCurrency);
        }

        /// <summary>
        /// Check whether the specified value is a double.
        /// </summary>
        /// <param name="name">Name of the parameter</param>
        /// <param name="value">Parameter value to validate</param>
        /// <param name="required">Paramater is required (adds an error if it's not specified)</param>
        /// <returns>value if parameter is a double; 0 if not.</returns>
        /// <param name="formatString">error string</param>
        protected double Double(string name, string value, bool required, string formatString)
        {
            if (string.IsNullOrEmpty(value) && required)
            {
                Errors.Add(name, Format(_validatorLang[FieldRequired], name));
                return 0;
            }

            double dvalue;
            if (!double.TryParse(value, out dvalue))
            {
                if (required || !string.IsNullOrEmpty(value))
                    Errors.Add(name, Format(_validatorLang[formatString], name));
                return 0;
            }

            return dvalue;
        }

        /// <summary>
        /// Check whether the specified value is an integer.
        /// </summary>
        /// <param name="name">Name of the parameter</param>
        /// <param name="value">Parameter value to validate</param>
        /// <param name="required">Paramater is required (adds an error if it's not specified)</param>
        /// <returns>value if parameter contains valid characters; string.Empty if not.</returns>
        /// <remarks>ascii 32-126, 128-167, 224-238.</remarks>
        public string AlphaNumeric(string name, string value, bool required)
        {
            if (name == null)
                throw new ArgumentNullException("name");

            if (string.IsNullOrEmpty(value) && required)
            {
                Errors.Add(name, Format(_validatorLang[FieldRequired], name));
                return string.Empty;
            }
            if (value == null)
                return string.Empty;

            foreach (char ch in value)
            {
                if (char.IsLetterOrDigit(ch) || ValidChars.IndexOf(ch) != -1) 
                    continue;

                Errors.Add(name, Format(_validatorLang[FieldAlphaNumeric], name));
                return string.Empty;
            }

            return value;
        }

        /// <summary>
        /// Check if a value is digits only
        /// </summary>
        /// <param name="name">Field name.</param>
        /// <param name="value">value to validate</param>
        /// <param name="required">true if field is required (may not be empty)</param>
        /// <returns>string if validated, otherwise string.Empty</returns>
        public string Digits(string name, string value, bool required)
        {
            return Digits(name, value, required, string.Empty);
        }

        /// <summary>
        /// Check if a value is digits only
        /// </summary>
        /// <param name="name">Field name.</param>
        /// <param name="value">value to validate</param>
        /// <param name="extraAllowedCharacters">extra characters that is allowed.</param>
        /// <param name="required">true if field is required (may not be empty)</param>
        /// <returns>string if validated, otherwise string.Empty</returns>
        public string Digits(string name, string value, bool required, string extraAllowedCharacters)
        {
            if (required && !Required(name, value) || value == null)
                return string.Empty;

            foreach (char ch in value)
            {
                if (char.IsDigit(ch) || extraAllowedCharacters.IndexOf(ch) != -1)
                    continue;

                if (extraAllowedCharacters == string.Empty)
                    Errors.Add(name, Format(_validatorLang[FieldDigits], name));
                else
                    Errors.Add(name, Format(_validatorLang[FieldDigitsExtra], name, extraAllowedCharacters));
                return string.Empty;
            }

            return value;
        }

        /// <summary>
        /// Validates a string to consist of letters.
        /// </summary>
        /// <param name="name">field name</param>
        /// <param name="value">value to validate</param>
        /// <param name="required">field is required</param>
        /// <returns>string if valid, string.Empty if not.</returns>
        public string Letters(string name, string value, bool required)
        {
            return Letters(name, value, required, " ");
        }

        /// <summary>
        /// Validates a string to consist of letters plus specified characters.
        /// </summary>
        /// <param name="name">The name of the parameter</param>
        /// <param name="value">The value to validate</param>
        /// <param name="required">If the value is required</param>
        /// <param name="extraAllowedCharacters">A string consisting of extra allowed characters</param>
        /// <returns>The validated string or string.Empty if validation failed</returns>
        public string Letters(string name, string value, bool required, string extraAllowedCharacters)
        {
            if (required && !Required(name, value) || value == null)
                return string.Empty;

            foreach (char c in value)
            {
                if (char.IsLetter(c) || extraAllowedCharacters.IndexOf(c) != -1)
                    continue;

                Errors.Add(name, Format(_validatorLang[FieldLettersSpecial], name, extraAllowedCharacters));
                return string.Empty;
            }

            return value;
        }

        /// <summary>
        /// Validates a string to be in trimmed hex letters
        /// </summary>
        /// <param name="name">The name of the parameter</param>
        /// <param name="value">The value to test</param>
        /// <param name="required">If the parameter is required</param>
        /// <returns>The value or string.Empty if validation failed</returns>
        public string Hex(string name, string value, bool required)
        {
            if (required && !Required(name, value) || value == null)
                return string.Empty;

            string lowercase = value.ToLower();
            foreach (char c in lowercase)
            {
                if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'))
                    continue;

                Errors.Add(name, Format(_validatorLang[FieldHex], name));
                return string.Empty;
            }

            return value;
        }

        /// <summary>
        /// validates email address using a regexp.
        /// </summary>
        /// <param name="name">field name</param>
        /// <param name="value">value to validate</param>
        /// <param name="required">field is required (may not be null or empty).</param>
        /// <returns>value if validation is ok; otherwise string.Empty.</returns>
        public string Email(string name, string value, bool required)
        {
            if (required && !Required(name, value))
                return string.Empty;
            if (string.IsNullOrEmpty(value))
                return string.Empty;

            if (Regex.IsMatch(value, EmailRegEx))
                return value;

            Errors.Add(name, Format(_validatorLang[FieldEmail], name));
            return string.Empty;
        }

		/// <summary>
		/// validates that a certain number is within the specified interval
		/// </summary>
		/// <param name="name">field name</param>
		/// <param name="value">value to validate</param>
		/// <param name="max">The maximum value that value is allowed to be</param>
		/// <param name="min">The minimum value that value is allowed to be</param>
		/// <param name="required">field is required (may not be null or empty).</param>
		/// <returns>value if validation is ok; otherwise 0.</returns>
		public int Between(string name, string value, int min, int max, bool required)
		{
			if (required && !Required(name, value))
				return 0;
			if (string.IsNullOrEmpty(value))
				return 0;

			if(min > max)
				throw new ArgumentException("Parameter min must be lower than parameter max", "min");

			int val;
			if(int.TryParse(value, out val))
			{
				if(val >= min && val <= max)
					return val;
			}

			Errors.Add(name, Format(_validatorLang[FieldBetween], name, min.ToString(), max.ToString()));
			
			return 0;
		}

		/// <summary>
		/// validates that a certain number is within the specified interval
		/// </summary>
		/// <param name="name">field name</param>
		/// <param name="value">value to validate</param>
		/// <param name="max">The maximum value that value is allowed to be</param>
		/// <param name="min">The minimum value that value is allowed to be</param>
		/// <param name="required">field is required (may not be null or empty).</param>
		/// <returns>value if validation is ok; otherwise 0.</returns>
		public double Between(string name, string value, double min, double max, bool required)
		{
			if (required && !Required(name, value))
				return 0;
			if (string.IsNullOrEmpty(value))
				return 0;

			if (min > max)
				throw new ArgumentException("Parameter min must be lower than parameter max", "min");

			double val;
			if (double.TryParse(value.Replace(',', '.'), NumberStyles.Any, CultureInfo.InvariantCulture, out val))
			{
				if (val >= min && val <= max)
					return val;
			}

			Errors.Add(name, Format(_validatorLang[FieldBetween], name, min.ToString(), max.ToString()));

			return 0;
		}

        /// <summary>
        /// Checks whether a field contains true (can also be in native language).
        /// </summary>
        /// <param name="name">field name</param>
        /// <param name="value">value to validate</param>
        /// <param name="required">field is required (may not be null or empty).</param>
        /// <returns>true if value is true; false if value is false or if validation failed.</returns>
        /// <seealso cref="FieldValueTrue"/>
        /// <remarks>Check validation errors to see if error ocurred.</remarks>
        public bool Boolean(string name, string value, bool required)
        {
            if (required && !Required(name, value))
                return false;

            if (string.IsNullOrEmpty(value))
                return false;
            if (value == "1"
                || string.Compare(value, "true", true) == 0
                || string.Compare(value, _validatorLang[FieldValueTrue], true) == 0)
                return true;
            if (value == "0"
                || string.Compare(value, "false", true) == 0
                || string.Compare(value, _validatorLang[FieldValueFalse], true) == 0)
                return false;

            Errors.Add(name, Format(FieldBoolean, name, FieldValueTrue, FieldValueFalse));
            return false;
        }

        /// <summary>
        /// Set default language.
        /// </summary>
        protected void SetDefaultMgr()
        {
            //Add all phrases to the manager.
            lock (lockObj)
            {
                if (Language == null)
                {
                    Language = new MemLanguageNode(1033, "Validator");
                    AddDefaultPhrases();
                }
            }
            _validatorLang = Language;
        }
    }

}

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 GNU Lesser General Public License (LGPLv3)

Share

About the Author

jgauffin
Founder Gauffin Interactive AB
Sweden Sweden
Founder of OneTrueError, a .NET service which captures, analyzes and provide possible solutions for exceptions.

blog | twitter

You may also be interested in...

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160621.1 | Last Updated 3 Sep 2008
Article Copyright 2008 by jgauffin
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid