← All articles
development

ModelBinding ASP.NET MVC and Multiple Field Validation

In ASP.NET MVC, add two ModelState errors -- one with an empty message -- to highlight both fields while showing only one validation message.

Donn Felker

Donn Felker

2010.08.17 · 1 min read · updated July 5, 2013

This tip comes to you from my blog, but the hat-tip goes to Andres Nelson whom I work with at my current client who actually showed me how to do this.

The Scenario

You have a grid with multiple fields. These fields are dependent upon each other. If one field is empty, then the other field is empty. At that point you want to display ONE error message informing the user that something is wrong, but you want to highlight both fields, as shown below in Figure 1-1. Please excuse the blurring of everything, but its NDA, you know how it goes. 🙂 Click for a larger view.

Figure 1-1: Highlighting both fields, but providing one error message.

Solution

I never thought of this, but its actually pretty simple, so again – hat tip to Andres. Simply add two ModelState errors, one for each property you want highlighted. However, for the second field, provide and empty string. MVC will not show that error in the validation summary, but the field will still get highlighted. Here’s the code –

bindingContext.ModelState.AddModelError("Field1Name", "Hey! Bad Stuffs Happens!");
// The one below will not show up in the validation summary, but the field will be highlighted.
bindingContext.ModelState.AddModelError("Field2Name", String.Empty);

That’s it!

Donn Felker

Written by Donn Felker

I've spent 25+ years shipping software, writing books, and running my own companies. I write about thinking clearly, working for yourself, and doing real work while AI rewrites the rules. New essays land here every week.

Get the newsletter

Keep reading