0

I know how to create a ValidationAttribute. But how can I check something based on the value of another property?

For example this model :

public class MyModel
{
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get;set; }
    [Required]
    public string Country { get; set; }
    [CustomValidator(ErrorMessage =  "If BE city cannot be null...")]
    public string City { get; set; }
}

Country is mandatory but if the Country == "BE" the property City cannot be null.

Is this possible with ValidationAttribute?

user7849697
  • 503
  • 1
  • 8
  • 19
  • 1
    Yes this is possible. [Check this answer](https://stackoverflow.com/questions/41900485/custom-validation-attributes-comparing-two-properties-in-the-same-model) – Jonesopolis Mar 21 '22 at 20:01
  • 1
    Possible, yes, but tricky: http://www.alessandrocolla.com/validate-a-value-based-on-the-value-of-another-property/ this is also interresting: https://stackoverflow.com/questions/7390902/requiredif-conditional-validation-attribute – Stefan Mar 21 '22 at 20:02

0 Answers0