Custom Validation

Example validating within a data layer 

I was having a conversation with a new .net colleague the other day and he indicated that he had learned about custom validators and was all excited about validating some properties within DTO's .  The validator pattern he was using however was designed for the Web app and not the data layer where most of our models and all of our DTO's resided.  So I showed him an alternative way to accomplish the same thing without corrupting his data layer by pulling in System.Web.  Below are both methods.


Here is the method he initially wanted to plop into the data project  - more aptly designed to work with a  web application  - since this method of course depends on System.Web - it would not be compatible with data layer.  Both methods accomplish the same thing.


namespace MyProject.ModelValidation
{
   [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
   public sealed class ValidFutureDate : ValidationAttribute, IClientValidatable
   {
        
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value != null)
            {
                DateTime _date = Convert.ToDateTime(value);
                if (_date < DateTime.Now)
                {
                    return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
                }
            }
            return ValidationResult.Success;
        }
     

      public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
      {
         ModelClientValidationRule mvr = new ModelClientValidationRule();
         mvr.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
         mvr.ValidationType = "validfuturedate";
         return new[] { mvr };
      }
   }
}

Here is the method I rewrote for him.




namespace MyProject.Data
{
    public class ValidateDateResult : ValidationAttribute
    {
        private readonly DateTime _minValue = DateTime.UtcNow;
        private readonly DateTime _maxValue = DateTime.UtcNow.AddYears(20);

        public override bool IsValid(object value)
        {
            DateTime val = (DateTime)value;
            return val >= _minValue && val <= _maxValue;
        }

        public override string FormatErrorMessage(string name)
        {
            return string.Format(ErrorMessage, _minValue, _maxValue);
        }
    }
}

Comments

Popular posts from this blog

Linq Exclude from separate list

Sorting Ascending and Descending

Linq Query Syntax vs Method Syntax