开发者

Error with validation for decimal datatype

开发者 https://www.devze.com 2022-12-24 18:29 出处:网络
This is my code for validation money type [Required(ErrorMessage = \"مبلغ پیشنهادی را وارد کنید\")]

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?


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+$

0

精彩评论

暂无评论...
验证码 换一张
取 消