ASP.NET MVC–How to show asterisk after required field label

Usually we have some required fields on our forms and it would be nice if ASP.NET MVC views can detect those fields automatically and display nice red asterisk after field label. As this functionality is not built in I built my own solution based on data annotations. In this posting I will show you how to show red asterisk after label of required fields.

Here are the main information sources I used when working out my own solution:

Although my code was first written for completely different situation I needed it later and I modified it to work with models that use data annotations. If data member of model has Required attribute set then asterisk is rendered after field. If Required attribute is missing then there will be no asterisk.

Here’s my code. You can take just LabelForRequired() methods and paste them to your own HTML extension class.

public static class HtmlExtensions
{
    [
SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types"
)]
   
public static MvcHtmlString LabelForRequired<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string labelText = ""
)
    {
       
return
LabelHelper(html,
           
ModelMetadata
.FromLambdaExpression(expression, html.ViewData),
           
ExpressionHelper
.GetExpressionText(expression), labelText);
    }

   
private static MvcHtmlString LabelHelper(HtmlHelper
html,
       
ModelMetadata metadata, string htmlFieldName, string
labelText)
    {
       
if (string
.IsNullOrEmpty(labelText))
        {
            labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split(
'.'
).Last();
        }

       
if (string
.IsNullOrEmpty(labelText))
        {
           
return MvcHtmlString
.Empty;
        }

       
bool isRequired = false
;

       
if (metadata.ContainerType != null
)
        {
            isRequired = metadata.ContainerType.GetProperty(metadata.PropertyName)
                            .GetCustomAttributes(
typeof(RequiredAttribute), false
)
                            .Length == 1;
        }

       
TagBuilder tag = new TagBuilder("label"
);
        tag.Attributes.Add(
           
"for"
,
           
TagBuilder
.CreateSanitizedId(
                html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)
            )
        );

       
if
(isRequired)
            tag.Attributes.Add(
"class", "label-required"
);

        tag.SetInnerText(labelText);

       
var output = tag.ToString(TagRenderMode
.Normal);


       
if
(isRequired)
        {
           
var asteriskTag = new TagBuilder("span"
);
            asteriskTag.Attributes.Add(
"class", "required"
);
            asteriskTag.SetInnerText(
"*"
);
            output += asteriskTag.ToString(
TagRenderMode
.Normal);
        }
       
return MvcHtmlString.Create(output);
    }
}

And here’s how to use LabelForRequired extension method in your view:

<div class="field"> 
    @Html.LabelForRequired(m => m.Name)
    @Html.TextBoxFor(m => m.Name)
    @Html.ValidationMessageFor(m => m.Name)

</div
>

After playing with CSS style called .required my example form looks like this:

LabelForRequired in action

These red asterisks are not part of original view mark-up. LabelForRequired method detected that these properties have Required attribute set and rendered out asterisks after field names.

NB! By default asterisks are not red. You have to define CSS class called “required” to modify how asterisk looks like and how it is positioned.

Liked this post? Empower your friends by sharing it!

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    6 thoughts on “ASP.NET MVC–How to show asterisk after required field label

    • June 28, 2012 at 2:06 pm
      Permalink

      This can be done with css alone by defining a class like this:
      .required:after { content:” *”; color: #f00; }

      Then apply the class to the HTML element

      @Html.TextBoxFor(m => m.Name)
      @Html.ValidationMessageFor(m => m.Name)

    • June 29, 2012 at 2:05 pm
      Permalink

      While I will agree that “hardcoding” the representation of what “required” will look like is not wise, in some situations (IE6 and IE7 come to mind) they don’t always work with CSS selectors and you have to look for other options.

    • June 29, 2012 at 5:07 pm
      Permalink

      Never smart to put styling (*) in your Html. If you want to change the required style (e.g. red box) than you are not so flexible.

    • July 9, 2012 at 2:36 pm
      Permalink

      I think this article’s point is ‘label of required fields’ of the Model and HTML5

    • July 30, 2012 at 10:10 pm
      Permalink

      Thanks for comments, guys! As a lazy guy who doesn’t want to fight with all those million ways how browsers are able to understand css I just worked out solution that works safely for most of them :)

      Michael shot straight to the heart of the problem and I want to add here some clients more: mobile browsers.

    Leave a Reply

    Your email address will not be published. Required fields are marked *