Mark Gilbert's Blog

Science and technology, served light and fluffy.

Too much of a good thing: ASP.NET MVC 2 Validation

Last week I came across a real stress-inducing issue with MVC 2 validation.  I had a Required field validator on a model property, and it wasn’t actually requiring a value in the field.  Here are the steps to reproduce it:

  1. Created blank MVC 2 app
  2. Add a resource file to the project, and put in some strings
  3. Add a HomeController
  4. Add a model called "Demo" with three fields, all required.  For the error messages, have one with an embedded error message (specified using the “ErrorMessageString” property of the Required attribute), one that references the resource file, and a third that does both.
  5. Add a Home/Index.aspx view, strongly-typed and based on the Demo model.  I created this as a “Create” view, so all of the validation controls were dropped in for me.  I then trimmed it back a bit to keep it simple.
  6. Run the app, and try to submit the form with nothing in any of the fields. 

You’ll see the first two Required validators light up, but the third one is silent.  In fact, the model state for that third field is "valid", even when it’s empty.  It’s also “valid” even if I explicitly call TryValidateModel in the postback action.

Now, this is a fairly contrived example, but it gets to the heart of the issue.  Model properties with a Required attribute should be, you know, required.

This was driving me nuts.  I pulled in a colleague, Joshua, and after some tinkering he suggested taking out the ErrorMessageString property for the third model property.  Amazingly that did the trick.  With both the ErrorMessageString and ErrorMessageResourceName properties of the Required() attribute set, the Field3 validation will never fail.  This appears to be an MVC2 issue – if I try this with MVC 3, it throws this exception when I post the form back:

    System.InvalidOperationException: Either ErrorMessageString or ErrorMessageResourceName must be set, but not both.

I would have expected one or the other fields to have taken priority, but the MVC 3 designers went another way with it – just throw an error and force the programmer to stop hedging his bets and pick one.  Apparently, too much validation is a bad thing?  Who knew.

A complete sample application showing this can be found in the “MVC2Validation.zip” archive at http://TinyURL.com/MarkGilbertSource.

Advertisements

May 2, 2012 - Posted by | ASP.NET MVC

Sorry, the comment form is closed at this time.

%d bloggers like this: