asp.net MVC3 Custom Validation
I am new to MVC so this question may be naive
I know you can add validation attributes to model properties and the framework will provide appropriate server side and client side validation.However I am forced to use a legacy database structure where one of the properties in the model is either "int" or "string" and the other property(Value) data type is determined by the first property.This means that I cannot use Annotations for validation. But is there any simple way of programatically "annotating" the properties after values are fetched from the databa开发者_JAVA百科se and the model class is constructed.If this can be done then it will do effective (client Side) validation without much hassle. thanks
This answer shows one way to inject attributes at runtime. Another answer shows how to use validations that are only checked sometimes.
In your case it would be pretty easy to do model-based validation.
For server-side validation:
public class MyModel: IValidatableObject
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public IEnumerable<ValidationResult>
Validate(ValidationContext validationContext)
{
var relevantFields = new [] {"Prop2"};
if (Prop1 == "Int" && NotValidInt(Prop2))
yield return new ValidationResult("Prop2 must be convertable to int", relevantFields);
else if (prop1 == "String" && NotValidString(Prop2))
yield return new ValidationResult("Prop2 must be convertible to string", relevantFields);
}
}
For client-side validation, it's a bit more involved but details are available here:
- MSDN article on adding support for clientside validation
- A Good StackOverflow answer on the topic
See the custom validation section of the free Pluralsight training on validation for more information on server-side validation.
You are falling into the normal newbie error of thinking of your database as the M in MVC. Any non-trivial app is going to require that you seperate your database model from your view model. So apply your attributes to a view model, then use business logic to copy the values to your database model when your view is properly validated.
MVC is a User Interface pattern, and databases do not belong in it... I know, every sample application under the sun passes your data objects to the view, but that's just not the way it should be done.
精彩评论