我正在处理ApplicationUser
的表单注册。在那里,我有像Facebook一样的Email or phone
字段。我正在使用DataAnnotation
进行模型验证。在Data annotation
我获得了[EmailAddress]
用于电子邮件验证,[Phone]
用于电话号码验证。但我需要像[EmailAddressOrPhone]
这样的东西。 那我怎么能实现呢?
public class RegisterViewModel
{
.....
[Required]
[Display(Name = "Email or Phone")]
public string EmailOrPhone { get; set; }
......
}
答案 0 :(得分:4)
您shouldn't use your own regex to validate email addresses,但我个人会使用以下逻辑来确定它是否是有效的电子邮件地址。如果它不是有效的电子邮件地址,您可以认为它是电话号码。
以下代码使用您已提及但在代码中的[EmailAddress]
属性。这样您就不必发明自己的验证电子邮件地址的方法。
public EmailOrPhoneAttribute : ValidationAttribute
{
public override IsValid(object value)
{
var emailOrPhone = value as string;
// Is this a valid email address?
if (this.IsValidEmailAddress(emailOrPhone))
{
// Is valid email address
return true;
}
else if (this.IsValidPhoneNumber(emailOrPhone))
{
// Assume phone number
return true;
}
// Not valid email address or phone
return false;
}
private bool IsValidEmailAddress(string emailToValidate)
{
// Get instance of MVC email validation attribute
var emailAttribute = new EmailAddressAttribute();
return emailAttribute.IsValid(emailOrPhone);
}
private bool IsValidPhoneNumber(string phoneNumberToValidate)
{
// Regualr expression from https://stackoverflow.com/a/8909045/894792 for phone numbers
var regex = new Regex("^\+?(\d[\d-. ]+)?(\([\d-. ]+\))?[\d-. ]+\d$");
return regex.IsMatch(phoneNumberToValidate)
}
}
当然,您需要确定自己如何确定电话号码是否正确,因为不同国家/地区的电话号码不同。我刚刚以this question的正则表达式为例。
答案 1 :(得分:2)
您可以使用Regex
来实现此目的。您必须合并电子邮件和电话的正则表达式。
public class RegisterViewModel
{
[Required]
[Display(Name = "Email or Phone")]
/* /<email-pattern>|<phone-pattern>/ */
[RegularExpression(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$|^\+?\d{0,2}\-?\d{4,5}\-?\d{5,6}", ErrorMessage = "Please enter a valid email address or phone number")]
public string EmailOrPhone { get; set; }
}
或者您可以创建自定义属性
public class EmailOrPhoneAttribute : RegularExpressionAttribute
{
public EmailOrPhoneAttribute()
: base(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$|^\+?\d{0,2}\-?\d{4,5}\-?\d{5,6}")
{
ErrorMessage = "Please provide a valid email address or phone number";
}
}
并使用
public class RegisterViewModel
{
[Required]
[Display(Name = "Email or Phone")]
[EmailOrPhone]
public string EmailOrPhone { get; set; }
}
答案 2 :(得分:1)
除自定义属性外,您还可以查看此库: https://github.com/jwaliszko/ExpressiveAnnotations
一个例子是:
[Required]
[AssertThat("IsEmail(EmailOrPhone) || (Length(EmailOrPhone) > 8 && Length(EmailOrPhone) < 16 && IsRegexMatch(EmailOrPhone, '^\\d+$'))",
ErrorMessageResourceType = typeof (Resources), ErrorMessageResourceName = nameof(Resources.EmailFormatInvalid))]
[Display(Name = "EmailOrPhone")]
public string EmailOrPhone { get; set; }
我在ExpressiveAnnotations中使用了AssertThat属性,并在Resources文件中创建了错误消息EmailFormatInvalid。