Validating Multiple Fields in ASP.NET MVC

ASP.NET MVC has the ability to validate forms with minimal effort thanks to the attributes in `System.ComponentModel.DataAnnotations` (https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/models-data/validation-with-the-data-annotation-validators-cs#using-the-data-annotation-validator-attributes). You can simply slap an attribute such as `Required` on a property and get nice validation messages. But what if you want to validate multiple fields on a model?

There are a couple ways you can solve this problem. One includes creating a Custom Attribute (https://msdn.microsoft.com/en-us/library/cc668224.aspx). This is a nice way to create re-usable attributes you can use on any of your models.

But what if your model has specific validation needs, where an attribute might not make sense? Sure, you could manually code the validation in your Controller’s Action:

^ This works, but you’d need to implement it for every action which takes `MyModel`

OR

You could implement this once using `ValidatableObject`.

Since `Validate` is called prior, `ModelState.IsValid` will be false.

As expected, the validation message is displayed after submitting the form.

Keep in mind that your `Validate` can return multiple `ValidationResult`s to handle complex validation rules for your model.

Here’s a sample project you can download and try yourself.

author avatar
Branden Barber Sr. Software Engineer
Branden (known as “Beebs” around the office) had the unique opportunity of testing the waters as a Don’t Panic Labs intern in 2011 while working toward his Computer Science degree at UNL. Don’t Panic Labs’s passion for building quality software and company culture is why he stuck around.

Related posts