2014-03-31 22 views
1

我有我的視圖模型上的屬性定義的[Phone]數據註釋:即使需要,電話數據註釋爲什麼不起作用?

public class ContactModel : BaseModel 
{ 
    [Required(ErrorMessage = "Please enter your first and last name.")] 
    [MaxLength(256, ErrorMessage = "Your name is too long, the maximum is 256 character.")] 
    public string Name { get; set; } 

    [Required(ErrorMessage = "Please enter your email address.")] 
    [EmailAddress(ErrorMessage = "Please enter a valid email address.")] 
    [MaxLength(256, ErrorMessage = "Your email address is too long, the maximum is 256 character.")] 
    [Display(Name = "Email Address")] 
    public string Email { get; set; } 

    [Phone(ErrorMessage = "Please enter a valid phone number.")] 
    [Display(Name = "Phone Number")] 
    public string Phone { get; set; } 

    [Required(ErrorMessage = "Please enter your comments or request.")] 
    [Display(Name = "Comments or Request")] 
    public string Comments { get; set; } 
} 

但像[Email]註解並沒有做它不驗證的格式;即使當[Required]。例如,如果我輸入文本123,則ModelState.IsValid仍然是true,因爲該屬性未驗證輸入。爲了增加對受傷的侮辱,客戶端沒有像電子郵件地址那樣發生任何事情。如果我輸入了無效的電子郵件地址,我實際上得到了JavaScript驗證 - 如預期的那樣。

發生了什麼事?

我使用Mvc 5.1.0.0,所以我已經更新到最新版本,以確保它不是特定於版本的。

+0

是不是'123'有效數字?如果你輸入'lsk​​afjlskj'會怎麼樣? –

回答

4

它事實上證實了。問題是123是一個有效的電話號碼,如果你嘗試輸入字母,你會注意到驗證失敗。但是,如果您輸入(123)234-2342它會成功...

這是因爲它必須爲世界各地的電話號碼工作。它甚至必須爲內部擴展(可能很容易2,3,4或5位數字)工作。特別是,如果你去這裏:

http://referencesource.microsoft.com/#System.ComponentModel.DataAnnotations/DataAnnotations/PhoneAttribute.cs

您將看到正則表達式可以讓幾乎任何數字。如果您想要進行美國特定電話驗證,那麼您應該只使用正則表達式屬性,或者根據此屬性開發自己的USPhoneAttribute。

+0

非常感謝朋友,這很有道理,我可能只是使用'Regex'屬性。 –

+0

更好的(權威的)鏈接來查看此類的內部將是http://referencesource.microsoft.com/System.ComponentModel.DataAnnotations/DataAnnotations/PhoneAttribute.cs.html上的Microsoft參考源。 –

+0

@ScottDorman - 謝謝,更新。 –

相關問題