Reputation: 6477
I have a Viewmodel with about 30 input properties with decimal regex validation ie:
[RegularExpression(@"\d+(\.\d{1,2})?", ErrorMessage = "Invalid decimal")]
public string strProperty { get; set; }
However I do not want to repeat this for every property. Is there a way to more central and DRY about this.
One idea is to define "\d+(.\d{1,2})?" as a constant.
Thanks....
Upvotes: 1
Views: 165
Reputation: 101483
One way that comes to mind is inherit from RegularExpressionAttribute
:
public class DecimalAttribute : RegularExpressionAttribute {
public DecimalAttribute() : base(@"\d+(\.\d{1,2})?") {
this.ErrorMessage = "Invalid decimal";
}
}
Then it becomes just:
[Decimal]
public string strProperty { get; set; }
That is assuming you know what you are doing and cannot just make property decimal
instead of string.
Upvotes: 2