Conditional data annotation

后端 未结 3 544
刺人心
刺人心 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:19

    I know this topic has some time, but if you'd like to use only declarative validation for that, you could just use such a simple construction (see this reference for further possibilities):

    [RequiredIf(DependentProperty = "party_type", TargetValue = "P")]
    public string surname { get; set; }
    
    public string party_type { get; set; }
    

    Update:

    Since the ExpressiveAnnotations 2.0, there is a breaking change. Now the same thing can be done in a simpler manner:

    [RequiredIf("party_type == 'P'")]
    public string surname { get; set; }
    

提交回复
热议问题