1

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....

SamJolly
  • 6,347
  • 13
  • 59
  • 125
  • 1
    following your idea of a `\d+(.\d{1,2})?` constant, you could implement a custom ValidationAttribute with this regex backed up in the validator. – sabotero Mar 20 '17 at 13:25
  • 2
    If all your properties have the same validation applied, it seems like you have a very odd model. Could you make a collection of sub-types instead? – DavidG Mar 20 '17 at 13:25
  • 2
    Declare the property as `float` or `decimal` and it will happen automatically. – GSerg Mar 20 '17 at 13:26

1 Answers1

2

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.

Evk
  • 98,527
  • 8
  • 141
  • 191
  • Thanks for this. I agree just using the "decimal" type is the ideal way however I got into difficulty regarding specifying a custom error message, hence my SO question: https://stackoverflow.com/questions/42904883/best-way-to-control-error-message-for-decimal-validation-in-viewmodel-property-v – SamJolly Mar 20 '17 at 13:32
  • I didn't work with asp.net for a long time, but what if you both apply this attribute AND make field decimal? – Evk Mar 20 '17 at 13:37