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 pro
If you write the 'column' annotation, will work fine
[Required]
[Column(TypeName = "decimal(18, 6)")]
public decimal Foo { get; set; }
[Range(1,(double) decimal.MaxValue, ErrorMessage="value should be between{1} and {2}."]
There is no explicit data annotation for a decimal so you need to use two separate ones to add constraints.
[RegularExpression(@"^\d+\.\d{0,2}$")]
This regular expression will make sure that the property has at most two decimal places.
[Range(0, 9999999999999999.99)]
Assuming you aren't accepting any negative numbers. Otherwise, replace 0 with -9999999999999999.99.
[RegularExpression(@"^\d+\.\d{0,2}$")]
[Range(0, 9999999999999999.99)]
public decimal Property { get; set; }
For a different approach which some may consider more readable, you can override the OnModelCreating method of your DbContext to set precision, like so:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<YourEntity>()
.Property(x => x.TheProprty)
.HasPrecision(18, 2);
}
Advantage: strongly typed vs custom regular expression
Disadvantage: can't see it on the class with just a scan
This seems to be the correct answer ( the above answers either restrict valid numbers that can be inserted into a data type of Decimal(18,2) or cause compile errors if you apply them to your code -- please confirm for yourself):
Use the following two constraints together:
Two Decimal Points
[RegularExpression(@"^\d+.?\d{0,2}$", ErrorMessage = "Invalid Target Price; Maximum Two Decimal Points.")]
Max 18 digits
[Range(0, 9999999999999999.99, ErrorMessage = "Invalid Target Price; Max 18 digits")]
Following on from @Schmalls example (and comment re building it into an attribute) I've created a working example (uses C# 6 string interpolation):
public class PrecisionAndScaleAttribute : RegularExpressionAttribute
{
public PrecisionAndScaleAttribute(int precision, int scale) : base($@"^(0|-?\d{{0,{precision - scale}}}(\.\d{{0,{scale}}})?)$")
{
}
}
Usage:
[PrecisionAndScale(6, 2, ErrorMessage = "Total Cost must not exceed $9999.99")]
public decimal TotalCost { get; set; }