How to Change ASP.NET MVC ValidationMessageFor from <span> to <label>

When it comes to providing a more usable interface for your user, I find that labels are the key. Being able to style a label as an error message and position it where you need it for your user is great, the added functionality being, if the user clicks on the label it lands their cursor nicely in the corresponding field [provided you have filled in the ‘for’ attribute].

When it comes to ASP.NET MVC, Microsoft made the choice to go with a <span> tag instead of the <label>.  I’m not sure why they made this decision, and please feel free to comment below if I’m breaking an html rule here, but a label for error validation just seems to be a no brainer to me.

If you feel the same here is a snippet of Code I created to be change a ValidationMessageFor Extension Method into a Method that provides the label error messaging.

I know that Regular Expression can cause some performance issues, and I don’t call myself a RegEx Master, so if you find a more efficient way to do this please Contact Me, and I will be sure to post the code change.

Remember: “friends don’t let friends __doPostBack();”

Happy Coding!

3 Responses

  • You mean something like [Textbox][<label for=textbox>Some Error</label>]?

    I’m no HTML pro, but I’m wondering if you can’t have more than one label per control? So if you had a label for the control, and then an error that is a label as well?

  • @Steve – I don’t think it would invalidate the HTML because the reference to the input field is set in an attribute. It wouldn’t quite matter for search engines as the second label doesn’t display until validation is triggered, it would just be a matter of how each browser handles the html. Thanks for the comment!

  • Corey,

    Excellent post, this helped me more than you can imagine. I so prefer <label> over <span> for the MVC validation. Thanks for taking the time to not only write it but to tell me about it when looking for help.

Leave a Reply