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

Nelssen picture Nelssen · Oct 22, 2015 · Viewed 7.1k times · Source

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

Answer

Sam.C picture Sam.C · Oct 22, 2015

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