7

my object has field with data type int. when i put in html form in this textbox letter not number the validator say- The field must be a number. how can i change this messages like this

 [Required(ErrorMessage = "Введите название")]
    [DisplayName("Название")]
    public int age { get; set; }
kusanagi
  • 14,296
  • 20
  • 86
  • 111

2 Answers2

4

I haven't found a clean way to achieve this using Data Annotations. One way would be to write a custom model binder but this seems like a lot of work to do for such a simple task.

Another way to achieve this is to add an App_GlobalResources folder to your ASP.NET application. Add a resource file called Messages.resx containing a PropertyValueRequired string resource.

PropertyValueRequired = "Some custom error message"

In your Application_Start register the resource class key:

protected void Application_Start()
{
    RegisterRoutes(RouteTable.Routes);
    DefaultModelBinder.ResourceClassKey = "Messages";
}

Note that ASP.NET MVC 2 uses the PropertyValueInvalid instead of PropertyValueRequired resource key.

IMO using Data Annotations to perform validation logic is limited (maybe in .NET 4 this will change). If you want to have full control over the validation logic I would recommend you using a validation library such as Fluent Validation or xVal.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • I have had exactly the same problem. I also moved from data annotations to Fluent Validation. I find fluent Validation really useful , and easy to customize. – Dai Bok Mar 23 '10 at 10:26
  • Any reasons why you recommend Fluentvalidation? Is it better than Enterprise Library Validation application block? BTW, xVal is currently deprecated. – Michael Freidgeim Jun 30 '12 at 00:29
  • I recommend FV because it is lightweight, allows to express complex validation rules in an elegant way, it provides an API for easily unit testing those validation rules and has a great integration with ASP.NET MVC. – Darin Dimitrov Jun 30 '12 at 06:57
2

I ran into the same problem and worked around it by specifying a RegularExpression that only allows positive natural numbers.

[Required(ErrorMessage = "Введите название")]
[DisplayName("Название")]
[RegularExpression(@"^[0-9]+$", ErrorMessage = "Поле возраст не является числом")]
public int age { get; set; }

Not sure if there are any downfalls to this solution. It seems to work fine for me.

PS: If you don't want to allow leading zeroes use "^[1-9]+[0-9]*$".

In retrospect: I have to admit though it's a bit weird to add a regular expression to an integer.

Matthijs Wessels
  • 6,530
  • 8
  • 60
  • 103