Created
January 9, 2022 19:30
-
-
Save edihasaj/d5a39c3da3d9f88c1c50535d8aa26ab3 to your computer and use it in GitHub Desktop.
C# Validate object recursively. Manual validation of property object.
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
public class CompositeValidationResult : ValidationResult | |
{ | |
private readonly List<ValidationResult> _results = new(); | |
public CompositeValidationResult(string errorMessage) : base(errorMessage) | |
{ | |
} | |
public CompositeValidationResult(string errorMessage, IEnumerable<string> memberNames) : base(errorMessage, | |
memberNames) | |
{ | |
} | |
protected CompositeValidationResult(ValidationResult validationResult) : base(validationResult) | |
{ | |
} | |
public IEnumerable<ValidationResult> Results => _results; | |
public void AddResult(ValidationResult validationResult) | |
{ | |
_results.Add(validationResult); | |
} | |
} |
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
public class ValidateObjectAttribute : ValidationAttribute | |
{ | |
protected override ValidationResult IsValid(object value, ValidationContext validationContext) | |
{ | |
if (value == null) return ValidationResult.Success; | |
var results = new List<ValidationResult>(); | |
if (value is not IEnumerable<object> list) | |
{ | |
var context = new ValidationContext(value, null, null); | |
Validator.TryValidateObject(value, context, results, true); | |
} | |
else | |
{ | |
foreach (var o in list) | |
{ | |
var context = new ValidationContext(o, null, null); | |
Validator.TryValidateObject(o, context, results, true); | |
} | |
} | |
if (results.Count == 0) return ValidationResult.Success; | |
var compositeResults = | |
new CompositeValidationResult( | |
$"{validationContext.DisplayName} {string.Join("; ", results.Select(r => r.ErrorMessage))}"); | |
results.ForEach(compositeResults.AddResult); | |
return compositeResults; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment