RequiredIf Conditional Validation Attribute

后端 未结 6 1191
长发绾君心
长发绾君心 2020-11-22 15:19

I was looking for some advice on the best way to go about implementing a validation attribute that does the following.

Model

public class MyInputMode         


        
6条回答
  •  盖世英雄少女心
    2020-11-22 15:53

    I know the topic was asked some time ago, but recently I had faced similar issue and found yet another, but in my opinion a more complete solution. I decided to implement mechanism which provides conditional attributes to calculate validation results based on other properties values and relations between them, which are defined in logical expressions.

    Using it you are able to achieve the result you asked about in the following manner:

    [RequiredIf("MyProperty2 == null && MyProperty3 == false")]
    public string MyProperty1 { get; set; }
    
    [RequiredIf("MyProperty1 == null && MyProperty3 == false")]
    public string MyProperty2 { get; set; }
    
    [AssertThat("MyProperty1 != null || MyProperty2 != null || MyProperty3 == true")]
    public bool MyProperty3 { get; set; }
    

    More information about ExpressiveAnnotations library can be found here. It should simplify many declarative validation cases without the necessity of writing additional case-specific attributes or using imperative way of validation inside controllers.

提交回复
热议问题