Search code examples
asp.net-mvcvalidationmodelstate

Validate an Object in ASP.NET MVC without passing it into an Action


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

Solution

  • 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
            }
        }