c# - Currency range and format validator for string field -
what correct currency data annotations following condition?
- numeric amount 2 decimal places.
- minimum amount $1.00; max amount $25000.00
here field.
public string amount {get; set;}
to check decimal places can use regularexpression annotation proper regex match number format:
[regularexpression(@"(\.\d{2}){1}$")]
to check minimum , maximum value must create our own custom attributes
[mindecimalvalue(1.00)] [maxdecimalvalue(25000.00)] public string amount { get; set; }
we can creating class deriving validationattribute , overriding isvalid method.
see implementation below.
[attributeusage(attributetargets.field | attributetargets.property, allowmultiple = false, inherited = true)] public class maxdecimalvalueattribute : validationattribute { private double maximum; public maxdecimalvalueattribute(double maxval) : base("the given value more maximum allowed.") { maximum = maxval; } public override bool isvalid(object value) { var stringvalue = value string; double numericvalue; if(stringvalue == null) return false; else if(!double.tryparse(stringvalue, out numericvalue) || numericvalue > maximum) { return false; } return true; } } [attributeusage(attributetargets.field | attributetargets.property, allowmultiple = false, inherited = true)] public class mindecimalvalueattribute : validationattribute { private double minimum; public mindecimalvalueattribute(double minval) : base("the given value less minimum allowed.") { minimum = minval; } public override bool isvalid(object value) { var stringvalue = value string; double numericvalue; if (stringvalue == null) return false; else if (!double.tryparse(stringvalue, out numericvalue) || numericvalue < minimum) { return false; } return true; } }
you can read more on how create own attributes, code needs more improvement.
hope helps!
Comments
Post a Comment