Nelssen
Nelssen

Reputation: 1157

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

Upvotes: 2

Views: 7841

Answers (2)

Andrei
Andrei

Reputation: 44640

You can use ValidateModel or TryValidateModel controller methods.

  • ValidateModel - throws exception if model is not valid.
  • TryValidateModel - returns bool which indicates if model is valid.

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

Sam.C
Sam.C

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

Related Questions