Use special characters in ModelState error message

Aug 26, 2009 · Follow on Twitter and Mastodon archive

In this post, let’s take a look at how to use special characters (like « and ») to model errors that we can use with ModelState.

My first approach was to avoid special characters in ModelState.AddModelError altogether, to be able to display messages in both a summary and next to the invalid control. However, I haven’t found a way to check if ModelState contains a certain model error.

My current workaround is to add the special characters to the message itself and not use a validation summary for the view.

However, this caused display problems, since the message is HTML encoded when this…

<%= Html.ValidationMessage("errorKey")%>

…is added to the page. «, for instance, will be displayed as plain text, and not as two left arrows.

The workaround for this is quite simple. Since the string is HTML encoded, simply decode any special characters like this:

var laquo = Server.HtmlDecode("&laquo;");
ModelState.AddModelError("errorKey", laquo + " Your custom message here");

This makes the view display the characters correctly. If you add the validation message to the right of the invalid control, the message will “point” at the control.

It would be nice to not include special characters in the validation string, but this requires that we can check if a certain error message exists.

Discussions & More

Please share any ideas, feedback or comments you may have in the Disqus section below, or by replying on Twitter or Mastodon.

If you found this text interesting, make sure to follow me on Twitter and Mastodon for more content like this, and to be notified when new content is published.

If you like & want to support my work, please consider sponsoring me on GitHub Sponsors.