From 963311ed00b8550933491944421f45d6a81228c0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 30 Jan 2022 13:18:53 -0600 Subject: recursively validate dictionary elements --- src/slskd/Common/Validation/ValidateAttribute.cs | 26 ++++++++++++++++++++++++ 1 file changed, 26 insertions(+) (limited to 'src/slskd/Common/Validation/ValidateAttribute.cs') diff --git a/src/slskd/Common/Validation/ValidateAttribute.cs b/src/slskd/Common/Validation/ValidateAttribute.cs index d731eb0e..c7efaa92 100644 --- a/src/slskd/Common/Validation/ValidateAttribute.cs +++ b/src/slskd/Common/Validation/ValidateAttribute.cs @@ -17,8 +17,10 @@ namespace slskd.Validation { + using System.Collections; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; + using System.Linq; /// /// Indicates that attributed properties should be recursively validated. @@ -35,6 +37,30 @@ namespace slskd.Validation var results = new List(); var context = new ValidationContext(value, null, null); + if (value.IsDictionary()) + { + var compositeResults = new CompositeValidationResult(validationContext.DisplayName); + + // given the context in this application, key type should never be anything but a string + foreach (string key in ((IDictionary)value).Keys) + { + var val = ((IDictionary)value)[key]; + var result = IsValid(val, new ValidationContext(val, null, null)); + + if (result != ValidationResult.Success) + { + compositeResults.AddResult(new CompositeValidationResult(key, new[] { result }.ToList())); + } + } + + if (compositeResults.Results.Any()) + { + return compositeResults; + } + + return ValidationResult.Success; + } + Validator.TryValidateObject(value, context, results, true); if (results.Count != 0) -- cgit v1.2.3