0

MSDN有an example of validating email address以下是它使用的RegEx。這是我見過的最好的RegEx,與其他所有人一樣,它將xx @ [IP地址]識別爲有效的電子郵件地址。我的問題是,我不能讓它在MVC3表單驗證中工作。 jQuery.validate.unobtrusive.js會拋出一個錯誤,提示「無效組」。有人經歷過這個?jQuery.validate.unobtrusive無法使用MSDN電子郵件地址RegEx

RegEx: 

^(?("")(""[^""]+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,17}))$ 

MVC 3 Model: 

[RegularExpression(@"^(?("")(""[^""]+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,17}))$", ErrorMessageResourceName = "ErrorInvalidEmail", ErrorMessageResourceType = typeof(OptInOutResource))] 
[Required] 
[DataType(DataType.EmailAddress)] 
[Display(Name = "lblUserName", ResourceType = typeof(MyResource))] 
public string UserName { get; set; } 

回答

0

你的正則表達式缺少等於在(?(問號後面的跡象(兩次出現)

試試這個:

^(?=("")(""[^""]+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?=(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,17}))$ 

他們的意思是看aheads (?=<regex>)

相關問題