10

Say I have a model that's annotated with [Required] fields etc in an MVC application.

It works great in the controller to just call ModelState.IsValid but say I'm not in the controller and would like to run similar checks elsewhere in my application on the model. Is it possible to somehow call this functionality another way?

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

// Code elsewhere in app that isn't the controller
MyModel model = new MyModel();
//Can I run a modelstate.isvalid type check here on model?  Would return false if Name wasn't set
Shaun Poore
  • 612
  • 11
  • 23

1 Answers1

21

Yes it is, using the TryValidateObject method on the Validator class in System.ComponentModel.DataAnnotations.

var results = new List<ValidationResult>();
var context = new ValidationContext(model, null, null);
if (!Validator.TryValidateObject(model, context, results))
{
    // results will contain all the failed validation errors.
}
Jason Berkan
  • 8,734
  • 7
  • 29
  • 39
  • 8
    Unfortunately, this validation doesn't recurse through any complex child objects or collections. The Validator.TryValidateObject(...) just does immediate property and field validations, and calls it a day, as opposed the the validation that happens on model binding in the Controller in MVC world which traverse the entire object graph. – neumann1990 Nov 03 '16 at 20:32
  • @neumann1990 Wouldn't passing a boolean on the last argument resolve this? There's an overload for [`TryValidateObject`](https://msdn.microsoft.com/en-us/library/dd411772(v=vs.110).aspx) with the documentation "**validateAllProperties** - true to validate all properties; if false, only required attributes are validated.". – Dan Atkinson Jun 05 '18 at 23:20
  • @DanAtkinson no. `validateAllProperties` does not control traversing the entire object graph. It controls whether or not the properties are all looked at, or just the required properties are looked at. You even mention that yourself. – Jake Smith Apr 09 '21 at 22:08
  • `DataAnnotations` are not the same as `ModelBinding.Validation`. Though I know its possible to duplicate the functionality with Data Annotations – Yarek T Mar 03 '22 at 17:29