2013-10-25 40 views
8

[Phone]屬性的默認有效格式是什麼? 在數據表中,電話列是navrchar(16) 如果我輸入電話號碼,如1112223333,我會得到「字段不是有效的電話號碼」。 如果我輸入01112223333,我會得到「價值'11112223333'是無效的。」DataAnnotations [電話]屬性

另外,如何覆蓋它呢? 我知道我可以做這樣的事情,但這是這種情況下的最佳做法嗎?

[RegularExpression(@"((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}",ErrorMessage="Invalid Phone Number!")] 

相關代碼:

[Required] 
    [Phone] 
    public string Phone { get; set; } 

    <div class="editor-field"> 
     @Html.EditorFor(model => model.Phone) 
     @Html.ValidationMessageFor(model => model.Phone) 
    </div> 

更新 我想有一個映射問題,當我從int改爲電話列navrchar。更新模型還不夠,所以我不得不使用Table Mapping手動更改該值。

錯誤2019:指定的成員映射無效。 類型爲'UserDBModel.UserProfile'的成員'Phone' 的類型'Edm.Int32 [Nullable = False,DefaultValue =]'與SqlServerCe.nvarchar'Nullable = False, Unicode'= True,FixedLength = False]成員'Phone'的' '類型爲'UserDBModel.Store.UserProfile'。

+1

這是一個很好的做法。如果您需要多次使用電話驗證,那麼最好創建自己的ValidationAttribute(PhoneNumberAttribute)。 – sjkm

+0

您將數據庫中的列更改爲'nvarchar',但將'Phone'屬性留在'UserDBModel.UserProfile'中'int' –

回答

9

PhoneAttribute默認正則表達式現在可以輕而易舉地通過使用新的(當前測試版).NET參考源發現:http://referencesource-beta.microsoft.com/#System.ComponentModel.DataAnnotations/DataAnnotations/PhoneAttribute.cs

在那裏,它示出了(難看)正則表達式爲被定義爲:

private static Regex _regex = new Regex(@"^(\+\s?)?((?<!\+.*)\(\+?\d+([\s\-\.]?\d+)?\)|\d+)([\s\-\.]?(\(\d+([\s\-\.]?\d+)?\)|\d+))*(\s?(x|ext\.?)\s?\d+)?$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture); 

這回答你的直接問題,但是否有幫助還有待觀察。也許這將是一個很好的基礎來創建自己的修改電話號碼正則表達式。

Sample Regex Matches

+0

該正則表達式的樣本編號是多少?我不能從正則表達式重新創建它。 – Megamind

+0

@Megamind,它有點鬆散。看到我上面的編輯。 –

6

試試這個 -

[Required(ErrorMessage = "Mobile no. is required")] 
    [RegularExpression("^(?!0+$)(\\+\\d{1,3}[- ]?)?(?!0+$)\\d{10,15}$", ErrorMessage = "Please enter valid phone no.")] 
    public string Phone { get; set; } 
相關問題