Ali
Ali

Reputation: 689

Error with validation for decimal datatype

This is my code for validation money type

    [Required(ErrorMessage = "مبلغ پیشنهادی را وارد کنید")]
    [RegularExpression("^[+]?\\d*$", ErrorMessage = "*")]
    public decimal FirstlySum { get; set; }

If I enter a word (such as "asdf") for the textbox corresponding to this property, I get the following error:

The value 'asdf' is not valid for FirstlySum.

The error message doesn't show.

How can I fix this?

Upvotes: 2

Views: 1470

Answers (1)

soniiic
soniiic

Reputation: 2685

This forum post describes two fixes to your solution.

The first is to set the type as an object and then run your regular expression on that. The second is to override the error message when you have access to the ModelState.

Preferably I'd go for declaring FirstlySum as an object type and then whenever you need to use this value you should use another property called something like FirstlySumTranslated which looks like this:

[Required(ErrorMessage = "مبلغ پیشنهادی را وارد کنید")]
[RegularExpression("^[+]?\\d*$", ErrorMessage = "*")]
public object FirstlySum { get; set; }


public decimal FirstlySumTranslated {
    get { return decimal.Parse(FirstlySum); }
}

Also note that your regular expression is not capturing numbers with a decimal place. For example, 1.23 is going to be regarded as an invalid value.

A regular expression that would work would be ^\+?(\d+\.)?\d+$

Upvotes: 1

Related Questions