Skip to content

Instantly share code, notes, and snippets.

@jpreece6
Created January 26, 2018 09:05
Show Gist options
  • Save jpreece6/9fe2c6ac72c21b611e7c8cfbbab4ac89 to your computer and use it in GitHub Desktop.
Save jpreece6/9fe2c6ac72c21b611e7c8cfbbab4ac89 to your computer and use it in GitHub Desktop.
Object validation attribute that tells the DataAnnotations validator that we want to validate a child object properties
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Utilities
{
// Credit http://www.technofattie.com/2011/10/05/recursive-validation-using-dataannotations.html
// Usage
//
// class ParentObject {
// [ValidateObject]
// public SubObjecy { get; set;}
// ...
// }
public class ValidateObjectAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var results = new List<ValidationResult>();
var context = new ValidationContext(value, null, null);
Validator.TryValidateObject(value, context, results, true);
if (results.Count != 0)
{
var errorMsg = (string.IsNullOrEmpty(ErrorMessage)) ? String.Format("Validation for {0} failed!", validationContext.DisplayName) : ErrorMessage;
var compositeResults = new CompositeValidationResult(errorMsg);
results.ForEach(compositeResults.AddResult);
return compositeResults;
}
return ValidationResult.Success;
}
}
public class CompositeValidationResult : ValidationResult
{
private readonly List<ValidationResult> _results = new List<ValidationResult>();
public IEnumerable<ValidationResult> Results
{
get
{
return _results;
}
}
public CompositeValidationResult(string errorMessage) : base(errorMessage) { }
public CompositeValidationResult(string errorMessage, IEnumerable<string> memberNames) : base(errorMessage, memberNames) { }
protected CompositeValidationResult(ValidationResult validationResult) : base(validationResult) { }
public void AddResult(ValidationResult validationResult)
{
_results.Add(validationResult);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment