/// <summary> /// Validates an object using a given <see cref="DataAnnotationsSpecProvider{T}" /> instance. /// </summary> public static void Validate <T>(this DataAnnotationsSpecProvider <T> specProvider, T instance) { Guard.ArgumentNotNull(specProvider, nameof(specProvider)); Guard.ArgumentNotNull(instance, nameof(instance)); var specs = specProvider.GetSpecifications(); var errors = specs.ToErrors(instance); if (errors.Any()) { throw new RuleException(@"Object violates specification.", errors); } }
protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value == null) { return(ValidationResult.Success); // can't validate rely on required attribute to ensure not null entity } // should look up by dictionary var type = value.GetType(); ISpecification <object>[] specs; // lazy load specs into internal cache if (SpecsCache.ContainsKey(type)) { specs = SpecsCache[type]; } else { var validator = new DataAnnotationsSpecProvider(type); specs = validator.GetSpecifications().ToArray(); SpecsCache.TryAdd(type, specs); } var errors = specs.ToErrors(value); if (errors.Any()) { var sb = new StringBuilder(); sb.AppendFormat("{0}:", _fieldName); foreach (var error in errors) { sb.AppendFormat(" {0}\n", error.Message); } ErrorMessage = sb.ToString(); return(new ValidationResult(ErrorMessage)); } return(ValidationResult.Success); }