Search code examples
c#asp.net-mvc-4asp.net-web-apicustom-attributes

How to put conditional Required Attribute into class property to work with WEB API?


I just want to put conditional Required Attribute which is work with WEB API

Example

public sealed class EmployeeModel
{
      [Required]
      public int CategoryId{ get; set; }
      public string Email{ get; set; } // If CategoryId == 1 then it is required
}

I am using Model State validation via (ActionFilterAttribute)


Solution

  • You can implement your own ValidationAttribute. Perhaps something like this:

    public class RequireWhenCategoryAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var employee = (EmployeeModel) validationContext.ObjectInstance;
            if (employee.CategoryId == 1)
                return ValidationResult.Success;
    
            var emailStr = value as string;
            return string.IsNullOrWhiteSpace(emailStr)
                ? new ValidationResult("Value is required.")
                : ValidationResult.Success;
        }
    }
    
    public sealed class EmployeeModel
    {
        [Required]
        public int CategoryId { get; set; }
        [RequireWhenCategory]
        public string Email { get; set; } // If CategoryId == 1 then it is required
    }
    

    This is just a sample. It may have casting issues, and I'm not sure this is the best approach to solve this problem.