ASP.MVC – Custom validation without using Data Annotations

This is intended as one of a series of posts on ASP.MVC 3 (Razor) about tips and traps as I learn, feel free to comment with advice or anything to help me or others.

All the ASP.MVC tutorials I’ve seen show validation being performed by using Data Annotations on the Model properties and calling ModelState.IsValid in the controller. This is great for normal validation but has some drawbacks when you need to do some complicated stuff.

I had a screen containing a radio button list, clicking a radio button hide or displayed certain fields, changing the mandatory fields for the screen. This made using the base MVC 3 Data Annotations not an option, as marking any of the fields as required would cause them to always be required regardless of the selected radio button. If this was something I would reuse I would probably create a custom validation attribute (link on how to do that) but it was only needed for that screen and quite specific.

Instead I used the ModelState.AddModelError, which allowed me to put my custom validation in the controller:

Capture

Some points to note:

  • The field name you supply in AddModelError is used by your “ValidationMessageFor” tags in the view, so will affect how control styles. Use a field name for a button/hidden field if you don’t want validation styles applied to a specific field control for the error.
  • If the field uses DataType validation (e.g. is an int/DateTime in model) and the value entered was invalid for the DataType using AddModelError will cause the DataType validation error message to display as well as your custom message.
Advertisements

2 thoughts on “ASP.MVC – Custom validation without using Data Annotations

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s