0

I have a field, I have added a regex for it. So this regex does not allow more than 7 digits before decimal and more than two digits after the decimal. this is working fine, it gives an error message properly. Now I want to give different-2 messages for before decimal points and after decimal points. If the user enters more than 7 digits of a numeric value, then the error message will come under the field as “Maximum 7 digits are allowed.” If the user enters more than 2 digits of the decimal value, then the error message will come under field as “Maximum 2 digits of decimals are allowed.”

[RegularExpression("^\\d{0,7}(\\.\\d{0,2})?$", ErrorMessage = "Please enter Comment in the right format.")]
public decimal? decimalField { get; set; }

Edit: Can we do something line like? https://stackoverflow.com/a/4803634/13211840

If not possible in MVC then how is it possible using javascript or jquery?

Vivek Nun
  • 1
  • 2

2 Answers2

0

I don't think so it's possible through data annotations. One approach could be, you explicitly validate your model and customize error message based on regex condition in your Action.

if (Regex.IsMatch("value", "regPattern"))
{
   ModelState.AddModelError("FieldName", "ErrorMessage");
}
dk1611
  • 11
  • 1
0

In your current pattern ^\\d{0,7}(\.\\d{0,2})?$ all parts are optional and will also match an empty string or a single dot as the decimal part accepts between 0 and 2 digits.

If you want to use 2 patterns for 2 different messages, you could match a pattern that allows 1-7 digits before the decimal and 1-2 digits after the dot.

If you want to allow a leading dot without a digit, you could use \\d{0,7} instead.

^\\d{1,7}(?:\\.\\d{1,2})?$

Regex demo


To match 1 to 7 digits:

^\\d{1,7}$
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • Perhaps this page can be helpful https://stackoverflow.com/questions/30392997/how-can-i-use-multiple-regex-expressions-with-different-validation-messages – The fourth bird Apr 12 '20 at 17:47