From d3392b72997f96732667b3df83e4cb6f15d7db1b Mon Sep 17 00:00:00 2001 From: Damian Edwards Date: Fri, 27 May 2022 15:18:31 -0700 Subject: [PATCH] Added MiniValidator.RequiresValidation() Bumped to version 0.6.0 --- src/Directory.Build.props | 2 +- src/MiniValidation/MiniValidator.cs | 32 +++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 8ff139b..19d6030 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -1,7 +1,7 @@ - 0.5.1 + 0.6.0 pre pre.$(BuildNumber) Damian Edwards diff --git a/src/MiniValidation/MiniValidator.cs b/src/MiniValidation/MiniValidator.cs index b20a2f5..9b621ff 100644 --- a/src/MiniValidation/MiniValidator.cs +++ b/src/MiniValidation/MiniValidator.cs @@ -1,6 +1,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Resources; @@ -15,6 +16,7 @@ namespace MiniValidation public static class MiniValidator { private static readonly TypeDetailsCache _typeDetailsCache = new(); + private static readonly IDictionary _emptyErrors = new ReadOnlyDictionary(new Dictionary()); /// /// Gets or sets the maximum depth allowed when validating an object with recursion enabled. @@ -22,6 +24,28 @@ public static class MiniValidator /// public static int MaxDepth { get; set; } = 32; + /// + /// Determines if the specified has anything to validate. + /// + /// + /// Objects of types with nothing to validate will always return true when passed to . + /// + /// The . + /// true to recursively check descendant types; if false only simple values directly on the target type are checked. + /// true if the has anything to validate, false if not. + /// + public static bool RequiresValidation(Type targetType, bool recurse = true) + { + if (targetType == null) + { + throw new ArgumentNullException(nameof(targetType)); + } + + return typeof(IValidatableObject).IsAssignableFrom(targetType) + || (recurse && typeof(IEnumerable).IsAssignableFrom(targetType)) + || _typeDetailsCache.Get(targetType).Any(p => p.HasValidationAttributes || recurse); + } + /// /// Determines whether the specific object is valid. This method recursively validates descendant objects. /// @@ -53,6 +77,14 @@ public static bool TryValidate(object target, bool recurse, out IDictionary(); var workingErrors = new Dictionary>(); var isValid = TryValidateImpl(target, recurse, workingErrors, validatedObjects);