Check if Model is valid outside of Controller

11,977

You could use the data annotations validation outside of an ASP.NET context:

public bool CreateCustomer(string[] data, out Customer customer)
{
    customer = new Customer();
    // put the data in the customer var

    var context = new ValidationContext(customer, serviceProvider: null, items: null);
    var results = new List<ValidationResult>();

    return Validator.TryValidateObject(customer, context, results, true);
}
Share:
11,977
James Santiago
Author by

James Santiago

Code and systems, systems and code

Updated on June 06, 2022

Comments

  • James Santiago
    James Santiago almost 2 years

    I have a helper class that is passed an array of values that is then passed to a new class from my Model. How do I verify that all the values given to this class are valid? In other words, how do I use the functionality of ModelState within a non-controller class.

    From the controller:

    public ActionResult PassData()
    {
        Customer customer = new Customer();
        string[] data = Monkey.RetrieveData();
        bool isvalid = ModelHelper.CreateCustomer(data, out customer);
    }
    

    From the helper:

    public bool CreateCustomer(string[] data)
    {
        Customter outCustomer = new Customer();
        //put the data in the outCustomer var
        //??? Check that it's valid
    
    }
    
  • neumann1990
    neumann1990 over 7 years
    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.