2012-03-04 90 views
15

我有這在我的視圖模型:使用數據註釋將小數點值驗證爲2位小數?

[Required(ErrorMessage = "Price is required")] 
[Range(0.01, 999999999, ErrorMessage = "Price must be greater than 0.00")] 
[DisplayName("Price ($)")] 
public decimal Price { get; set; } 

我想驗證用戶不輸入超過2位小數。所以我想有

有效值:12,12.3,12.34

無效值:12,12.345

有沒有辦法用數據註解來驗證這一點?

回答

19

你可以使用正則表達式的屬性,與您的條件匹配一個正則表達式。這裏有一大堆涉及數字的表達,我相信一個人會適合這個賬單。這裏是link

這將讓你開始,雖然它可能不是你想要的(至少需要一個數字導致小數點)爲包容性:

[RegularExpression(@"\d+(\.\d{1,2})?", ErrorMessage = "Invalid price")] 

請注意,這是很難發出精確的錯誤消息因爲你不知道正則表達式的哪個部分不匹配(例如,字符串「z.22」具有正確的小數位數,但不是有效的價格)。

+1

對於帶有句點(。)以外的小數點分隔符的語言,例如,逗號(14,6),因爲RegularExpression將十進制轉換爲使用當前文化的字符串。 – jahav 2015-06-01 15:24:43

+0

'^ \ d *(\。|,|(\。\ d {1,2})|(,\ d {1,2}))?$'同時使用句點和逗號,在點之前的前面的數字或在該點之後的後面的數字。 – helrich 2016-03-04 13:21:10

+0

出於某種原因,給定正則表達式允許我插入多個小數點,例如:1.22.3.44 – Storm 2016-04-06 06:44:52

2

您可以通過使用正則表達式使這個驗證,並與正則表達式屬性應用它。

4
[RegularExpression(@"^\d+(\.\d)?$", ErrorMessage = "It cannot have more than one decimal point value")] 
[Range(0.1,100)] 
public double xyz{get;set;}   

它爲我的作品高達一個十進制值

18
[RegularExpression(@"^\d+.\d{0,2}$",ErrorMessage = "Price can't have more than 2 decimal places")] 
public decimal Price { get; set; } 

這將滿足0至2位小數,或根本沒有。

+0

您可能想要轉義'。' (這意味着「任何字符」,如果沒有轉義)給予^ \ d + \。\ d {0,5} $ – Appetere 2012-07-27 10:32:11

+2

糟糕,意思是^ \ d + \。?\ d {0,5} $與'?'只允許0或1次重​​復。 – Appetere 2012-07-27 10:41:25

+0

這實際上並不允許一個沒有小數位的值,即'10',**但是**,它不允許有一個小數點:'10。 – mattytommo 2015-04-21 10:41:00

4

您也可以創建自己的十進制驗證屬性,從RegularExpressionAttribute繼承:

public class DecimalAttribute : RegularExpressionAttribute 
{ 
    public int DecimalPlaces { get; set; } 
    public DecimalAttribute(int decimalPlaces) 
     : base(string.Format(@"^\d*\.?\d{{0,{0}}}$", decimalPlaces)) 
    { 
     DecimalPlaces = decimalPlaces; 
    } 

    public override string FormatErrorMessage(string name) 
    { 
     return string.Format("This number can have maximum {0} decimal places", DecimalPlaces); 
    } 
} 

並註冊它啓用的Application_Start)客戶端驗證(:

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(DecimalAttribute), typeof(RegularExpressionAttributeAdapter)); 
0

我有同樣的方案爲OP,但提供不給,對所有的下列情況下有效的解決方案的答案:

12, 12.3 and 12.34

爲了做到這一點,我們用下面的正則表達式:

[RegularExpression(@"^\d+(.\d{1,2})?$")] 
0

類似mattytommo。你需要逃避'。' - 否則將接受任何字符

[RegularExpression(@"^\d+(\.\d{1,2})?$")]