Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Model is valid outside of Controller

Tags:

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  } 
like image 760
James Santiago Avatar asked Jun 22 '12 04:06

James Santiago


People also ask

For which model state is valid validate?

ModelState. IsValid indicates if it was possible to bind the incoming values from the request to the model correctly and whether any explicitly specified validation rules were broken during the model binding process.

Should validation be done in controller?

If you're validating data on server side, And your validation does not require application business logic (i.e you're not checking to see if the user has enough credit in his account), You should validate in the controller.

How can we check whether our model is valid or not at the controller level?

You need to check whether the submitted data is valid or not in the controller. In other words, you need to check the model state. Use the ModelState. IsValid to check whether the submitted model object satisfies the requirement specified by all the data annotation attributes.


1 Answers

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); } 
like image 113
Darin Dimitrov Avatar answered Oct 04 '22 00:10

Darin Dimitrov