0

In my Mvc5 test project I have a model with a property like the following:

[Required]
[DisplayName("Codigo Cliente")]
public int ClientCode{ get; set; }

the default error message when the user enteres a letter of special character in the editor is:

The field Codigo Cliente must be a number.

How can I modify this? in this case I need to change the language, but in case that I wanted to show a more specific error what can I do?

I have tried with the DataType attribute but the Enum does not have a value that applys for this case (numbers)

mmilan
  • 1,738
  • 8
  • 31
  • 57
  • did you try to specifiy the message with [Required(ErrorMessage="Please ...")] – NicoD Jul 02 '14 at 15:32
  • Possible duplicate of http://stackoverflow.com/questions/2480557/providing-localized-error-messages-for-non-attributed-model-validation-in-asp-ne – rsenna Jul 02 '14 at 15:35
  • @NicoD that would only show the error message if the user does not fill in a value in the editor – mmilan Jul 02 '14 at 15:42

3 Answers3

3

Use Range:

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.rangeattribute.aspx

Or use IntegerOnly from Data Annotations Extensions

http://dataannotationsextensions.org/Integer/Create

Artur Kedzior
  • 3,994
  • 1
  • 36
  • 58
2

The simplest way I found to solve this issue is use String with Range attribute in Data Annotation Model like specify below.

    [Required]
    [Range(0, int.MaxValue, ErrorMessage = "Codigo Cliente must be a positive or negative non-decimal number.")]
    [DisplayName("Codigo Cliente")]
    public string ClientCode { get; set; }

In Range attribute you can specify your custom Error Message. For Interger use int.MaxValue , For double use double.MaxValue like so on. I hope this will help you a lot.

Dilip Langhanoja
  • 4,455
  • 4
  • 28
  • 37
-1

If you want to specify a message you must use this

[Required(ErrorMessage = "your message")]

If you want to use a lang. based message is not that easy. You can use multiple resource file (for every language you need) and try a custom error binder that extends the DefaultModelBinder and make an override of the method BindModel(), there you can make your custom validation ad use your custom language message.

theLaw
  • 1,261
  • 2
  • 11
  • 23
  • 1
    This would show the message when the user does not provide a value. what I want is to change the message when a user enters an invalid value. IE a letter in an editor that accepts integers – mmilan Jul 02 '14 at 16:33
  • 1
    Using a custom error binder you can validate the value, read all the response. – theLaw Jul 03 '14 at 12:37