Created
January 26, 2018 09:05
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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