开发者

DataAnnotations Automatic Handling of int is Causing a Roadblock

开发者 https://www.devze.com 2023-01-02 14:12 出处:网络
Summary: DataAnnotation\'s automatic handling of an \"int?\" is making me rethink using them at all. Maybe I\'m missing something and an easy fix but I can\'t get DataAnnotations to cooperate. I have

Summary: DataAnnotation's automatic handling of an "int?" is making me rethink using them at all.

Maybe I'm missing something and an easy fix but I can't get DataAnnotations to cooperate. I have a public property with my own custom validation attribute:

[MustBeNumeric(ErrorMessage = "Must be a number")]
public int? Weight { get; set; }

The point of the custom validation attribute is do a quick check to see if the input is numeric and display an appropriate error message. The problem is that when DataAnnotations tries to bind a string to the int? is automatically doesn't validate and displays a "The value 'asdf' is not valid for Weight."

For the life of me I can't get DataAnnotations to stop handling that so I can take care of it in my custom attribute.

This seems like it would be a popular scenario (to validate that the input in numeric) and I'm guessing there's an eas开发者_运维知识库y solution but I didn't find it anywhere.


Here's a workaround (as I wouldn't really call this a solution). Add a Messages.resx file inside the App_GlobalResources folder of your web application. Add the following resource inside:

Key: PropertyValueInvalid
Value: {0} Must be a number

In the Application_Start method of Global.asax add the following:

DefaultModelBinder.ResourceClassKey = "Messages";
0

精彩评论

暂无评论...
验证码 换一张
取 消