Say I have a model that's annotated with [Required] fields etc in an MVC application.
It works great in the controller to just call ModelState.IsValid but say I'm not in the controller and would like to run similar checks elsewhere in my application on the model. Is it possible to somehow call this functionality another way?
class MyModel{
[Required]
public string Name{get;set;}
}
// Code elsewhere in app that isn't the controller
MyModel model = new MyModel();
//Can I run a modelstate.isvalid type check here on model? Would return false if Name wasn't set
That's because an error exists; ModelState. IsValid is false if any of the properties submitted have any error messages attached to them. What all of this means is that by setting up the validation in this manner, we allow MVC to just work the way it was designed.
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. In your example, the model that is being bound is of class type Encaissement .
AddModelError("Region", "Region is mandatory"); ModelState. IsValid will then return false.
Yes it is, using the TryValidateObject
method on the Validator
class in System.ComponentModel.DataAnnotations
.
var results = new List<ValidationResult>();
var context = new ValidationContext(model, null, null);
if (!Validator.TryValidateObject(model, context, results))
{
// results will contain all the failed validation errors.
}
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