From f07ab51c89202d6d6213f44ba7e6cffe3ad16732 Mon Sep 17 00:00:00 2001 From: "philippe.hauber" Date: Tue, 10 Oct 2017 17:25:36 +0200 Subject: [PATCH] Add function to know if a field is required --- .../Attributes/RequiredIfAttribute.cs | 24 +++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/src/ExpressiveAnnotations/Attributes/RequiredIfAttribute.cs b/src/ExpressiveAnnotations/Attributes/RequiredIfAttribute.cs index 3c76c13..dfbdeed 100644 --- a/src/ExpressiveAnnotations/Attributes/RequiredIfAttribute.cs +++ b/src/ExpressiveAnnotations/Attributes/RequiredIfAttribute.cs @@ -61,19 +61,39 @@ protected override ValidationResult IsValidInternal(object value, ValidationCont { AssertNonValueType(value); - var isEmpty = value is string && string.IsNullOrWhiteSpace((string) value); + var isEmpty = value is string && string.IsNullOrWhiteSpace((string)value); if (value == null || (isEmpty && !AllowEmptyStrings)) { Compile(validationContext.ObjectType); if (CachedValidationFuncs[validationContext.ObjectType](validationContext.ObjectInstance)) // check if the requirement condition is satisfied return new ValidationResult( // requirement confirmed => notify FormatErrorMessage(validationContext.DisplayName, Expression, validationContext.ObjectInstance), - new[] {validationContext.MemberName}); + new[] { validationContext.MemberName }); } return ValidationResult.Success; } + /// + /// Indicates if the property is required with respect to the attribute and model value + /// + /// Model value to test + /// + /// True if the property is required, false otherwise + /// + public bool IsRequired(object value) + { + if (value == null) + return false; + + Type type = value.GetType(); + if (!CachedValidationFuncs.ContainsKey(type)) + { + CachedValidationFuncs[type] = Parser.Parse(type, Expression); + } + return CachedValidationFuncs[type](value); + } + private void AssertNonValueType(object value) { if (PropertyType == null)