How to validate one field related to another's value in ASP .NET MVC 3

前端 未结 3 414
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 07:40

I had two fields some thing like phone number and mobile number. Some thing like..

    [Required]
    public string Phone { get; set; }

    [Required]
    p         


        
3条回答
  •  一个人的身影
    2020-11-28 08:14

    I know this question is not so hot, because it was asked relatively long time ago, nevertheless I'm going to share with a slightly different idea of solving such an issue. 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.

    Your problem can be defined and automatically solved by the usage of following annotations:

    [RequiredIf("Mobile == null",
        ErrorMessage = "At least email or phone should be provided.")]
    public string Phone{ get; set; }
    
    [RequiredIf("Phone == null",
        ErrorMessage = "At least email or phone should be provided.")]
    public string Mobile { get; set; }
    

    If you feel it would be useful for your purposes, more information about ExpressiveAnnotations library can be found here. Client side validation is also supported out of the box.

提交回复
热议问题