views:

150

answers:

2

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 easy solution but I didn't find it anywhere.

A: 

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";
Darin Dimitrov
Yikes. Not exactly seamless. I'm tempted to change those properties on my view models that are ints to strings. Then I can run them through the DataAnnotations validations as well a few custom attributes and if they're good to go convert them to an int when I map from view model to entity. In your opinion, does that sound like a decent solution?
DM
thx for the insight.
DM
A: 

Can I see what MustBeNumeric looks like? I'm trying to do the same thing and can't even get that far :/

James in Indy