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?

2
  • It's not possible in single attribute, you would need to write your own JavaScript code for this. Commented Apr 12, 2020 at 13:19
  • @MichałTurczyn can we break the regex into two regex? Commented Apr 12, 2020 at 14:25

2 Answers 2

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");
}
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Perhaps this page can be helpful stackoverflow.com/questions/30392997/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.