views:

64

answers:

4

I have a int property in my class and want to validate if the user has entered a string. How can I do that using data annotations? When I pass a non-integer value I get a excpetion like this:

The value 'asdasd' is not valid for property.

Any Ideas?

A: 

You could put a Range-attribute on your model-field like so:

[Range(0, 9999)]
public int Something {get; set;}

Now whenever the user inputs a string it will not validate, and also the int must be between 0-9999

this should also work with

[Range(0, 9999)]
public string Something {get; set;}

and

[Range(0, 9999)]
public object Something {get; set;}
Yngve B. Nilsen
A: 

I've put

[Range(0, Int32.MaxValue, ErrorMessage="Invalid Number")]
public int? Number { get; set; }

but I've got this message from an excpetion

The value 'aaa' is not valid for Number.
Murilo Lima
Friendly advice - edit your existing question with this extra information rather than adding it as an answer.
Dan Diplo
+1  A: 

http://www.asp.net/mvc

That's about as useful as posting "http://www.google.com/" as an answer to all questions. At least link to a relevant page.
Sohnee
+2  A: 

There are two stages of validation at play here.

Before the validation set up in your attributes is called, the framework first attempts to parse the information.

So here are a couple of examples based on this code:

[Range(0, Int32.MaxValue, ErrorMessage="Invalid Number")]
public int? Number { get; set; }

I type nothing into the box...

"Invalid Number" (Framework will create a null integer, your validation rule fails)

I type "A" into the box...

"The value 'A' is not valid for Number." (Framework cannot convert "A" into a nullable int, so the framework validation rule fails and your validation rule it not checked.

** Solutions **

1 - Live with the default message until you are using MVC 3 / .NET 4, which makes it easier to override these messages

2 - Exclude the value from the binder, so it won't cause an error (but you will have to bind it and check it yourself)

[Bind(Exclude="MyNumber")]

3 - Make it a string on the model, then test it with a TryParse and add your own custom model error (This is a reasonable practice and reminds us all why View Models are used rather than Domain Objects!)

if (!Int32.TryParse("MyNumber", out myInteger)) {
    ModelState.AddModelError("MyNumber", "That isn't a number!");
}

There are actually lots of solutions, but I would say go with option 3 for now.

Sohnee