Asp.net
MVC 4 - DataAnnotations - 類型驗證
我有以下程式碼工作
[Required(ErrorMessage = "Price is required.")] [Range(typeof(Decimal), "1", "9999", ErrorMessage = "Price xx.xx")] public decimal? productPrice { get; set; }當頁面送出時 Price = EMPTY Field 錯誤消息是“Price is required.”。價格 = 超過 9999 錯誤消息是“價格 xx.xx”。
但是,當我鍵入“aaaa”時,錯誤消息是 “該欄位 productPrice 必須是數字”。
如果輸入不正確,如何更改消息?比如:“價格必須是 1-9999 之間的小數/數字。
—- 更新:—- 下面的程式碼使用
NULL,非十進制,介於範圍之間,但不適用於“.1”。
[Required(ErrorMessage = "Price is required.")] [RegularExpression(@"[0-9]*\.?[0-9]+", ErrorMessage = "Price must be a Numbers only.")] [Range(typeof(Decimal), "1", "9999", ErrorMessage = "Price must be a decimal/number between {1} and {2}.")] public decimal? productPrice { get; set; }
您可以嘗試使用正則表達式:
[RegularExpression(@"[0-9]*\.?[0-9]+", ErrorMessage = "{0} must be a Number.")]您還可以嘗試數據註釋擴展: http ://dataannotationsextensions.org/Home/Wiki
或者編寫自己的實現,如下所示: https ://github.com/srkirkland/DataAnnotationsExtensions/blob/master/DataAnnotationsExtensions/DigitsAttribute.cs
使用正則表達式更新 (匹配 $ 9,999.99 | $ 0.70 | .1)
[RegularExpression(@"^\$?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}[0-9]{0,}(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$", ErrorMessage = "{0} must be a Number.")]或者使用 Range 對@Martin 的建議稍作修改(實際上是一個更好的解決方案):
[Range(typeof(Decimal), "0", "9999", ErrorMessage = "{0} must be a decimal/number between {1} and {2}.")]