on asp.net mvc3 I'm using dataanotations for validation. I control the validations on my controller with a simple if(ModelState.IsValid). How can I control those validations in a simple class, not a controller?
Thanks!
on asp.net mvc3 I'm using dataanotations for validation. I control the validations on my controller with a simple if(ModelState.IsValid). How can I control those validations in a simple class, not a controller?
Thanks!
This is pretty much what the MVC validator does behind the scenes:
This will iterate through all the annotations and figure our if there are any errors and add them to an error collection. It's best to put this in a base class then have all your other classes inherit from it. if GetErrors().Any()
returns true, the model is invalid.
public IEnumerable<ErrorInfo> GetErrors() {
return from prop in TypeDescriptor.GetProperties(this).Cast<PropertyDescriptor>()
from attribute in prop.Attributes.OfType<ValidationAttribute>()
where !attribute.IsValid(prop.GetValue(this))
select new ErrorInfo(prop.Name, attribute.FormatErrorMessage(string.Empty));
}
Error Info Class:
public class ErrorInfo{
public string Name { get; set; }
public string FormatErrorMessage { get; set; }
public ErrorInfo(string name, string formatErrorMessage){
Name = name;
FormatErrorMessage = formatErrorMessage;
}
}
Use the validator helper class: http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.validator.aspx