7

Say I have a model property like this:

[Range(1, 31, ErrorMessage = "O dia de fechamento deve possuir valores entre 1 e 31")]
public int DataInicial { get; set; }

Even with a custom error message set on the annotation, I'm still getting the default error message for the Range annotation "Please enter a value less than or equal to 31.", when I type something like "32" or more at the @Html.TextBoxFor(model => model.DataInicial) field.

I'm aware of this post, but I think if you can set custom messages at annotation level, It should work without setting an App_GlobalResources and a .resx file, setting third-party libraries or whatever... I know that adding a .resx file and put all those validation strings there, is a "best-practice", but...

So, where I could be wrong, since the messages are not showing correctly?

Thank you in advance.

Community
  • 1
  • 1
cezarlamann
  • 1,465
  • 2
  • 28
  • 43
  • What is the error message you are seeing? – Gjohn Sep 18 '14 at 17:58
  • client side or server side validation? – Alex Art. Sep 18 '14 at 17:59
  • Client-side validation (the one that occurs before POSTing the form). I got "Please enter a value less than or equal to 31." when I type "32" into the form field which have Range validation, as I said above. Where do I need to change to customize this message? – cezarlamann Sep 18 '14 at 18:47
  • 1
    4 years later this is still an issue. I am seeing this error message: Please enter a value greater than or equal to 1 with this decoration on an int: [Range(1, 9999, ErrorMessage = "Attribute Number must be between 1 and 9999"] Inspecting my page I see this: data-val-range="Attribute Number must be between 1 and 9999" So unobtrusive validation should be working but it isn't. Interestingly I also have this validation: data-val-number="The field Code must be a number." Yet when I enter a letter I still see the same error: Please enter a value greater than or equal to 1 – BGTurner May 29 '19 at 10:02

1 Answers1

-1

I was running into the same issue and experimented a little. Just learning MVC myself and it wasn't too obvious, but the solution seems nice and makes sense. The issue just comes down to which validation attribute gets triggered.

I found ErrorMessage is specific to the validation it is associated with.

A simple example should make it real clear...

[Required(ErrorMessage="xxx may not be blank.")]
[Range(0.0,1000.0,ErrorMessage="The value entered must be 0 to 1000.00")]
public virtual double xxx ()  // snip...

If empty, upon validation you will get "xxx may not be blank". While a value has been entered but not valid you should see the other error "The value entered...".

Andrew
  • 7,602
  • 2
  • 34
  • 42
Dano
  • 112
  • 7
  • The question is about the custom error message not overriding the default error message for Range. Your answer has nothing to do with this question. – Hoots Dec 06 '17 at 14:16