Conditional data annotation

后端 未结 3 549
刺人心
刺人心 2021-02-04 02:08

Is there a way to make a data annotation conditional? I have a table Party where I store both organisations and persons. If I\'m adding an organisation I don\'t w

3条回答
  •  心在旅途
    2021-02-04 02:18

    You can make your model inherit from IValidatableObject and then put your custom logic into the Validate method. You'll have to remove the RequredAttribute from the property as well. You will have to write some custom javascript to validate this rule on the client as the Validate method doesn't translate into the unobtrusive validation framework. Note I changed your properties to strings to avoid casting.

    Also, if you have other validation errors from attributes, those will fire first and prevent the Validate method from being run so you only detect these errors if the attribute-based validation is ok.

    public class Party : IValidatableObject
    {
        [DisplayName("Your surname")]
        public string surname { get; set; }
    
        [DisplayName("Type")]
        public string party_type { get; set; }
        ...
    
        public IEnumerable Validate( ValidationContext context )
        {
             if (party_type == "P" && string.IsNullOrWhitespace(surname))
             {
                  yield return new ValidationResult("Surname is required unless the party is for an organization" );
             }
        }
    }
    

    On the client you can do something like:

     
    

提交回复
热议问题