好吧,我有2个独立的正则表达式,分别用于验证电子邮件和电话号码。喜欢
email = "^\w+\@([\da-zA-Z\-]{1,}\.){1,}[\da-zA-Z-]{2,6}"
和
phone = "^[2-9]\d{2}-\d{3}-\d{4}"
但是,我想输入一个字段输入,可以是电子邮件和电话。我必须验证它们。 我尝试过使用||这两个resex之间或之间的运算符,但没有工作。
[Required]
[MaxLength(50)]
[RegularExpression(@"^\w+\@([\da-zA-Z\-]{1,}\.){1,}[\da-zA-Z-]{2,6} || ^[2-9]\d{2}-\d{3}-\d{4}$", ErrorMessage = "Invalid Phone number Email Address")]
[Display(Name = "Phone number or Email")]
[System.Web.Mvc.Remote("IsUserExists", "Account", HttpMethod = "POST", ErrorMessage = "This Phone number or Email already exists")]
public string MobOrEmail { get; set; }
所以我需要一个正确的正则表达式,它可以同时验证电子邮件或电话号码。或者他们之间的操作是完美的,我需要它很糟糕。感谢。
答案 0 :(得分:1)
您需要一个|
(管道)字符(不是2)并且没有空格。它应该是
[RegularExpression(@"^\w+\@([\da-zA-Z\-]{1,}\.){1,}[\da-zA-Z-]{2,6}|[2-9]\d{2}-\d{3}-\d{4}", ErrorMessage = "...")
参考regexr
请注意,您发送的正则表达式不是很强大。 jquery.validate.js
使用的是
/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$
为了使这在模型中更容易阅读,并且更容易重用,您可以创建自己的属性,扩展ReqularExpressionAttribute
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class EmailOrPhoneAttribute : RegularExpressionAttribute
{
public EmailOrPhoneAttribute () : base(@"^\w+\@([\da-zA-Z\-]...etc")
{
// Add default error message
ErrorMessage = "Invalid Phone number Email Address";
}
}
并在global.asax.cs
protected void Application_Start()
{
....
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailOrPhoneAttribute), typeof(RegularExpressionAttributeAdapter));
....
}
然后在模型中
[EmailOrPhone]
public string MobOrEmail { get; set; }