root/StructuredWeb/StructuredWeb/Validation/ValidationFramework/Result/ValidationResult.cs

User picture

Author: marisic.net

Revision: 112 («Previous)


File Size: 2.11 KB

(February 15, 2009 21:44 UTC) Over 3 years ago


  

 
Show/hide line numbers
#region Using Statements

using System.Collections.Generic;
using System.Linq;

#endregion

namespace StructuredWeb.ValidationFramework.Result
{
    public sealed class ValidationResult
    {
        private bool _dirty = true;
        private bool _valid;

        public ValidationResult()
        {
            Messages = new List<ValidationMessage>();
        }

        public bool Valid
        {
            get
            {
                //theoretically O(n) time but in pratice will be constant time
                //Still, no need for multiple traversals, Traverse only if it's changed
                if (_dirty)
                {
                    _valid = Messages.Count(msg => msg.Warning == false) == 0;
                    _dirty = false;
                }

                return _valid;
            }
        }

        public IList<ValidationMessage> Messages { get; internal set; }

        /// <summary>
        /// Adds the error. Allows users to add custom messages after validation.
        /// Enterprise Library validation doesn't allow this which can cause the need
        /// to marshal message objects around instead of being able to bind this collection.
        /// </summary>
        /// <param name="errorMessage">The error message.</param>
        public void AddError(string errorMessage)
        {
            _dirty = true;
            Messages.Add(new ValidationMessage {Message = errorMessage});
        }


        /// <summary>
        /// Adds the warning. Allows users to add custom messages after validation.
        /// Enterprise Library validation doesn't allow this which can cause the need
        /// to marshal message objects around instead of being able to bind this collection.
        /// </summary>
        /// <param name="warningMessage">The warning message.</param>
        public void AddWarning(string warningMessage)
        {
            //No need to mark collection dirty since warnings never generate validation changes
            Messages.Add(new ValidationMessage {Message = warningMessage, Warning = true});
        }
    }
}