c# - 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;}
}
解决方案
我建议解决此问题的最佳方法之一是使用 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));
}
推荐阅读
- polymer - 如何在 Polymer-3.x 中单击按钮时触发 Iron-ajax?
- solidity - TypeError:测试solidity合约时无法读取未定义的属性“调用”
- html - 如何使多行上的内联块显示得很好
- docker - docker:两阶段构建中的变量
- ios - GraphQL Object mapping Apollo with different schema by target
- angular - Aggrid-如何添加数据绑定masterDetailComponent
- primefaces - 找不到 AdminFaces 的 theme.css 资源
- python - 为多个 celery worker 和线程正确设置 Flask-SQLAlchemy
- javascript - 如何强制 'asp:Image' 加载新的 'imageUrl' ?
- django - Elasticsearch 的问题:ConnectionError