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 }
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.
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.
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.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With