2

How can i run all DataAnnotation validations on model?

I'm building a model instance from code and i don't have no modelstate binding or anything. I just want to run all my validations against it... I am using EF CodeFirst.

public class Category
{
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }
}

cat = new Category();
if (cat.IsValid()) { /* blah */ } // i want something like this

I know it's probably a stupid question but i can't seem to find an answer anywhere..

alexcepoi
  • 708
  • 1
  • 10
  • 19
  • possible duplicate of [Unit Testing ASP.NET DataAnnotations validation](http://stackoverflow.com/questions/2167811/unit-testing-asp-net-dataannotations-validation) – KyleMit Feb 09 '15 at 22:48

2 Answers2

5

This is similar to this question about unit testing data annotations. You could add an extension method similar to this:

public static class ValidationExtension {

    public static bool IsValid<T>(this T model) where T: class {
        var validationResults = new List<ValidationResult>();
        var validationContext = new ValidationContext(model, null, null);
        Validator.TryValidateObject(model, validationContext, validationResults, true);
        return validationResults.Count == 0;
    }
}
Community
  • 1
  • 1
bkaid
  • 51,465
  • 22
  • 112
  • 128
0

The title of this question includes ASP.net MVC.

Please be aware that the Validator class and MVCs validation has subtle differences.

For example:

  1. DataAnnotations.Validator doesn't support buddy class out of box.
  2. MVC can be configured to use another validation framework for example FluentValidation.

If you want to run MVC's validation and populate the ModelState, you can call the TryValidateModel or ValidateModel.

if you don't want to populate the ModelState, use this code snippet in your controller.

 var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType());
 ModelValidator.GetModelValidator(metadata, ControllerContext).Validate(null);
LostInComputer
  • 15,188
  • 4
  • 41
  • 49