首页 > 解决方案 > How to Apply either one has required Field in Data Annontation in C#?

问题描述

I have scenario where i need to apply either one(Email or Phone) has required field. Both Can not be null or Empty.

This is my Class.

 public class Contact 
 {
    public Email Email {get; set;}
    public Phone Phone {get; set;}
 }


public class Email
{
 [Required]
 public string EmailAddress {get;set;}
}

public class Phone 
{
[Required]
public int CountryCode {get; set;}

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

标签: c#validationannotationsdata-annotations

解决方案


我建议解决此问题的最佳方法之一是使用 Remote 属性,这将允许您根据特定方法验证您的值以确定有效性:

删除验证属性

[Remote("IsPhoneOrEmail", "YourController", ErrorMessage = "Not a valid phone or e-mail!")]
public string Notification { get; set;}

它调用一个特定的方法来执行你的验证:

public ActionResult IsPhoneOrEmail(string notification) 
{
     Regex phoneRegex = new Regex(@"^([0-9\(\)\/\+ \-]*)$");
     Regex emailRegex = new Regex("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");

     return (emailRegex .IsMatch(notification) || phoneRegex.IsMatch(notification));
}

推荐阅读