ASP.NET Core Validation with Component Model Attributes

It might not be the most exciting thing in the world but there's a lot of great stuff in the System.ComponentModel.DataAnnotations namespace. Last month, I wrote about using Component Model attributes to customize how ASP.NET Core forms are displayed. This month, I'm going to talk about using Component Model attributes to do validation in ASP.NET Core.

New Fields: Email & Notes
I'm going to keep using the same sample application and just add some more stuff to it. If you're looking for the code, it's available in this GitHub repository.

My first addition to the demo application is to add a couple of new properties to the Person class -- a field for storing the person's email address and a field for some miscellaneous notes. So that gives us a Person class with the properties you see in the class diagram below.

[Click on image for larger view.]

These fields are just regular old string properties that I've added the DisplayAttribute to.

[Display(Name = "Email Address")]
public string Email { get; set; } = string.Empty;

[Display(Name = "Notes")]
public string Notes { get; set; } = string.Empty;

Validation with Minimal Effort
This is an ASP.NET MVC application and there's a razor (cshtml) file that handles the Person editor page. All those little attributes on the label, input, and span tags that start with "asp-" are used by ASP.NET Core to add helpful stuff to the HTML that gets generated for you. One of those things that you get by default is validation.

[Click on image for larger view.]

When you run the application and click the save button on the Person editor, you'll get validation error messages for any invalid fields.

[Click on image for larger view.]

Customizing Validation Using Attributes
At the moment, the validations are pretty basic. For example, the email address validator doesn't care about what I type in there -- it just has to not be blank. If we want to actually check that the email address value is a valid email address, we can do that by adding the EmailAddressAttribute to that property.

It's an unbelievably simple change -- just go to the Person class, and add [EmailAddress] to the Email property.

[Click on image for larger view.]

When you restart the application, you get proper email address validation. Previously just typing "asdf" would have been fine because it satisfied the non-empty string validation rule that we get by default. Now, typing "asdf" gives us a validation error message that says that it's not a valid email address.

[Click on image for larger view.]

Notes Can Be Empty or Less Than X Characters
The next validation that I wanted to add was making the Notes property be optional but then also limit the number of characters that are allowed. In this case, I picked a pretty short note length of only 25 characters.

Since this isn't a required field, it doesn't have the [Required] attribute. You might think that adding [Required(AllowEmptyStrings = true)] would work but it just doesn't work in ASP.NET. To enforce the length limit, you can add [StringLength(25)].

[Click on image for larger view.]

Now when I run the application, it automatically blocks me from typing more than 25 characters in that Notes field.

[Click on image for larger view.]

Minor Gotcha
There's a little bit of a catch here with that "optional string field" thing. If your optional field is a nullable string type (string?), you're all set. But in my case, I didn't want to make that property nullable -- I wanted to avoid nulls and make string.Empty be a valid value. In order to make that work, you'll need to change the configuration of ASP.NET Core to allow optional non-nullable value types.

The basic gist of it is that you need to modify the Program.cs file for your ASP.NET Core project to use SuppressImplicitRequiredAttributeForNonNullableReferenceTypes. For more details, check out this blog post.

builder.Services.AddControllersWithViews(options =>
{
    options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true;
});

Summary
So that's the quick overview of using Component Model Attributes for ASP.NET Core validation. There's so much more you can do with the stuff in the System.ComponentModel.DataAnnotations namespace including lots more different types of validations.

Anyway, I hope you found this interesting.

If you looking for the source code, it's available on GitHub.

About the Author

Benjamin Day is a consultant, trainer and author specializing in software development, project management and leadership.

Posted by Benjamin Day on 05/20/2025


Keep Up-to-Date with Visual Studio Live!

Email address*Country*