0

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!

elranu
  • 2,292
  • 6
  • 31
  • 55

3 Answers3

1

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;

 }
}
Chris Kooken
  • 32,730
  • 15
  • 85
  • 123
1

Answered Here (w/ .net 4): Using ASP.Net MVC Data Annotation outside of MVC

Community
  • 1
  • 1
Joe
  • 5,389
  • 7
  • 41
  • 63
1

Use the validator helper class: http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.validator.aspx

jgauffin
  • 99,844
  • 45
  • 235
  • 372