Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Data annotation for a Decimal(18,2)

I have a column inside my sql server 2008 wih type of Decimal(18,2). But on entity framework what is the best data annotation validation I can apply to this property, inside my asp.net MVC web application ?

like image 503
John John Avatar asked Nov 06 '13 11:11

John John


People also ask

What data type should I use for decimals?

The Decimal data type provides the greatest number of significant digits for a number. It supports up to 29 significant digits and can represent values in excess of 7.9228 x 10^28. It is particularly suitable for calculations, such as financial, that require a large number of digits but cannot tolerate rounding errors.

How do you create a data type for decimals?

For instance, decimal (4,2) indicates that the number will have 2 digits before the decimal point and 2 digits after the decimal point, something like this has to be the number value- ##. ##.


1 Answers

There is no explicit data annotation for a decimal so you need to use two separate ones to add constraints.

Two Decimal Points

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

This regular expression will make sure that the property has at most two decimal places.

Max 18 digits

[Range(0, 9999999999999999.99)] 

Assuming you aren't accepting any negative numbers. Otherwise, replace 0 with -9999999999999999.99.

Result

[RegularExpression(@"^\d+(\.\d{1,2})?$")] [Range(0, 9999999999999999.99)] public decimal Property { get; set; } 
like image 57
ediblecode Avatar answered Sep 30 '22 20:09

ediblecode