diff options
| author | JP Dillingham <jp@dillingham.me> | 2024-10-28 20:18:34 -0500 |
|---|---|---|
| committer | JP Dillingham <jp@dillingham.me> | 2024-10-28 20:18:34 -0500 |
| commit | 88955fb1e597b08d802710063cd40da987c44d78 (patch) | |
| tree | 6a58135fdc010716bf7c5e8c80c8624459f8a794 | |
| parent | e21eb94376f242145b07b49c923f2f997d83611c (diff) | |
| download | slskd-88955fb1e597b08d802710063cd40da987c44d78.tar.gz | |
update ValidationAttribute to work with arrays
| -rw-r--r-- | src/slskd/Common/Validation/ValidateAttribute.cs | 36 |
1 files changed, 29 insertions, 7 deletions
diff --git a/src/slskd/Common/Validation/ValidateAttribute.cs b/src/slskd/Common/Validation/ValidateAttribute.cs index c7efaa92..540e61bc 100644 --- a/src/slskd/Common/Validation/ValidateAttribute.cs +++ b/src/slskd/Common/Validation/ValidateAttribute.cs @@ -17,6 +17,7 @@ namespace slskd.Validation { + using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; @@ -34,22 +35,43 @@ namespace slskd.Validation return ValidationResult.Success; } + // note: here's a great place to log the type and value if there are issues: + // Console.WriteLine($"{value.GetType()}: {value.ToJson()}"); var results = new List<ValidationResult>(); var context = new ValidationContext(value, null, null); - if (value.IsDictionary()) + // we should only be using dictionaries and arrays (e.g. []), not IEnumerable, because the YAML library + // somehow has nondeterministic behavior, sometimes turning YAML arrays into arrays, and sometimes List + // this could be handled by checking for List<T> but let's just keep it simple and remember to use arrays + if (value.IsDictionary() || value is Array) { 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) + if (value.IsDictionary()) { - var val = ((IDictionary)value)[key]; - var result = IsValid(val, new ValidationContext(val, null, null)); + // 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) + if (result != ValidationResult.Success) + { + compositeResults.AddResult(new CompositeValidationResult(key, new[] { result }.ToList())); + } + } + } + else if (value is Array array) + { + for (int i = 0; i < array.Length; i++) { - compositeResults.AddResult(new CompositeValidationResult(key, new[] { result }.ToList())); + var val = array.GetValue(i); + var result = IsValid(val, new ValidationContext(val, null, null)); + + if (result != ValidationResult.Success) + { + compositeResults.AddResult(new CompositeValidationResult(i.ToString(), new[] { result }.ToList())); + } } } |
