Reputation: 40182
How does one accomplish "model-level" validation as stated in Brad Wilson's post:
Finally, if you want a validation to have access to multiple properties, then make it a model-level validation (so that it gets the entire model as the model parameter, rather than a single individual property value).
From http://forums.asp.net/p/1457591/3650720.aspx
I tried to do the following
[MyCustomValidation("SomeStuff")]
public class MyClass
{
// properties
}
Breakpoints place in the IsValid
override of MyCustomValidation
trigger nothing, the code just continues. Breakpoints in the constructor of MyCustomValidation
work, but nothing after that.
Is this not what model-level validation
refers to?
dirtygopher's link to http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html shows model validation, the only issue is that the validation attributes are placed on the child properties of the parent class.
I'm looking for a way to place validation-attributes
directly to the class as I demonstrated in my above example.
Upvotes: 5
Views: 2505
Reputation: 379
The is another answer to this question if you are using MVC3. This example creates an attribute that can be attached to a single property and make it dependend on another property by passing the property name and object value.
The result is more elegant because the attribute is attached to the object that is actually validated.
http://blogs.msdn.com/b/simonince/archive/2011/02/04/conditional-validation-in-asp-net-mvc-3.aspx
Upvotes: 0
Reputation: 927
Here is good post in Brad Wilson's blog http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html. I hope it will help you to understand model-level validation concept.
Upvotes: 0
Reputation: 1388
There's a good example for this in the RegisterModel that comes with the latest asp.net mv 2.
Look at the "PropertiesMustMatch" attribute and its usage.
Upvotes: 2