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
}
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);
}