Rendering DataAnnotation Attributes For Forms In Umbraco

Published on
-
1 min read

When developing custom forms in Umbraco using ASP.NET Core’s Tag Helpers and DataAnnotations, I noticed that display names and validation messages weren’t being rendered for any of the fields.

[Required(ErrorMessage = "The 'First Name' field is required.")]
[Display(Name = "First Name")]
public string? FirstName { get; set; }

[Required(ErrorMessage = "The 'Last Name' field is required.")]
[Display(Name = "Last Name")]
public string? LastName { get; set; }

[Required(ErrorMessage = "The 'Email Address' field is required.")]
[Display(Name = "Email Address")]
public string? EmailAddress { get; set; }

This was quite an odd issue that (if I'm honest!) took me quite some time to resolve as I followed my usual approach to building forms — an approach I’ve used many times in Umbraco without any issues. The only difference in this instance was that I was using an Umbraco form wrapper.

@using (Html.BeginUmbracoForm<ContactFormController>("Submit"))
{
    <fieldset>
        <!-- Form fields here -->
    </fieldset>
}

I must have been sitting under a rock as I have never come across this from the years working in Umbraco. It could be down to the fact that the forms I have developed in the past didn't rely so heavily on .NET's DataAnnotation attributes.

The only solution available to remedy this problem was to install a Nuget package (currently in beta) that has kindly been created by Dryfort.com, which resolves the display name and validation attributes for in-form rendering.

The Nuget package works in Umbraco 10 onwards. I've personally used it in version 13 without any problem. Until there is an official Umbraco fix, this does the job nicely and highly recommended if you encounter similar issues.

Before you go...

If you've found this post helpful, you can buy me a coffee. It's certainly not necessary but much appreciated!

Buy Me A Coffee

Leave A Comment

If you have any questions or suggestions, feel free to leave a comment. Your comment will not only help others, but also myself.