Reputation: 45135
Does anyone know how to simply run a model instance through the model state validation mechanism?
I just want to reuse the system for something different. I have some models that I read configuration files into and I'd like to decorate them with data annotation attributes and validate the configuration file is setup properly.
Upvotes: 0
Views: 153
Reputation: 4000
Then you want to run System.ComponentModel.DataAnnotations.Validator
. I think this is what gets called under the hoods.
Say you have a class like this:
public class Customer
{
[Required]
public string FirstName { get; set; }
}
You can then validate this object by running the following code:
[Test]
public void Test()
{
var customer = new Customer();
var results = new List<ValidationResult>();
var valid = Validator.TryValidateObject(customer, new ValidationContext(customer), results, true);
valid.ShouldBe(false);
results.Count.ShouldBe(1);
}
Upvotes: 1