Created
September 22, 2020 15:25
-
-
Save smailliwcs/f94975668033af954cbd89283e3fcaeb to your computer and use it in GitHub Desktop.
Conditional required validation
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
using System.ComponentModel.DataAnnotations; | |
using System.Reflection; | |
public sealed class ConditionalRequiredAttribute : RequiredAttribute | |
{ | |
public override bool RequiresValidationContext | |
{ | |
get { return true; } | |
} | |
public string ConditionalPropertyName { get; private set; } | |
public ConditionalRequiredAttribute(string conditionalPropertyName) | |
{ | |
ConditionalPropertyName = conditionalPropertyName; | |
} | |
protected override ValidationResult IsValid(object value, ValidationContext validationContext) | |
{ | |
PropertyInfo conditionalProperty = validationContext.ObjectType.GetProperty(ConditionalPropertyName); | |
bool conditionalValue = (bool)conditionalProperty.GetValue(validationContext.ObjectInstance); | |
if (conditionalValue) | |
{ | |
return base.IsValid(value, validationContext); | |
} | |
else | |
{ | |
return ValidationResult.Success; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment