Reputation: 1157
In ASP.NET MVC you can validate the model passed to an Action with ModelState.IsValid()
.
I'd like to validate arbitrary objects rather than the one Model passed in. How can I do that, using the framework's libraries?
public ActionResult IsValidSoFar()
{
// Get a user's autosaved data
var json = await ...
HomeModel model = JsonConvert.Deserialize<HomeModel>(json);
// Validate the model <---- How?
}
public class HomeModel
{
[Required, MaxLength(100)]
public string Name { get; set; }
}
Upvotes: 2
Views: 7841
Reputation: 44640
You can use ValidateModel or TryValidateModel controller methods.
IMPORTANT: If you validate list of models one by one, you probably would like to reset ModelState for each iteration by calling ModelState.Clear();
Please see my question regarding this: Validate list of models programmatically in ASP.NET MVC
Upvotes: 3
Reputation: 1621
you can use ValidationContext class ... like below
var context = new ValidationContext(modelObject);
var results = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(modelObject, context, results);
if (!isValid)
{
foreach (var validationResult in results)
{
//validation errors
}
}
Upvotes: 7