Monthly Archives: May 2018

Conditional Required Validation in ASP.NET MVC

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;
        }
    }
}