Introduction
A web form should do more than receive data from the browser. Users can submit missing, incorrectly formatted, or business-rule-breaking values at any time. Validation is therefore an essential part of both user experience and application security.
In this lesson, we will validate an article creation form for a content management application built with ASP.NET Core MVC and .NET 8. We will begin with Data Annotations for required fields, length limits, email format, and numeric ranges. We will then add business rules that cannot be expressed by a single built-in attribute. Finally, we will use ModelState, Validation Tag Helpers, and accessible messages to make the form clear and usable.
Validation operates at two levels. Client-side validation provides fast feedback, but it is not a security boundary. Server-side validation must run for every request because a client can disable JavaScript or send a manually crafted request.
1. Creating a validation model
Start with a ViewModel for the form. Instead of binding the database entity directly, expose only the fields that the user is allowed to submit. This continues the secure form design approach introduced in the previous lesson.
using System.ComponentModel.DataAnnotations;
namespace CmsApp.ViewModels;
public class ArticleCreateViewModel
{
[Required(ErrorMessage = "The title is required.")]
[StringLength(120, MinimumLength = 5,
ErrorMessage = "The title must be between 5 and 120 characters.")]
[Display(Name = "Title")]
public string Title { get; set; } = string.Empty;
[Required(ErrorMessage = "The summary is required.")]
[StringLength(300, MinimumLength = 20,
ErrorMessage = "The summary must be between 20 and 300 characters.")]
[Display(Name = "Summary")]
public string Summary { get; set; } = string.Empty;
[Required(ErrorMessage = "The author email is required.")]
[EmailAddress(ErrorMessage = "Enter a valid email address.")]
[Display(Name = "Author email")]
public string AuthorEmail { get; set; } = string.Empty;
[Range(1, 60, ErrorMessage = "Reading time must be between 1 and 60 minutes.")]
[Display(Name = "Reading time")]
public int ReadingMinutes { get; set; }
[Display(Name = "Publish date")]
public DateTime? PublishAt { get; set; }
}
Required prevents an empty value. StringLength limits minimum and maximum character counts. EmailAddress checks the basic email format. Range restricts a numeric value to a defined interval. Display supplies a user-friendly field name for labels and messages.
With non-nullable reference types, ASP.NET Core may treat some properties as implicitly required. Relying on implicit behavior can make messages less clear. Explicit validation attributes and explicit messages are easier to understand and localize, especially in bilingual applications.
2. The validation flow in a controller
The GET action displays the form. The POST action receives the bound ViewModel and checks the validation result. When the model is invalid, the same View is returned with the submitted model so that the user sees both the original values and the validation messages.
using CmsApp.ViewModels;
using Microsoft.AspNetCore.Mvc;
namespace CmsApp.Controllers;
public class ArticlesController : Controller
{
[HttpGet]
public IActionResult Create()
{
return View(new ArticleCreateViewModel
{
PublishAt = DateTime.Today.AddDays(1),
ReadingMinutes = 5
});
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(ArticleCreateViewModel model)
{
if (model.PublishAt.HasValue && model.PublishAt.Value.Date < DateTime.Today)
{
ModelState.AddModelError(
nameof(model.PublishAt),
"The publish date cannot be earlier than today.");
}
if (!ModelState.IsValid)
{
return View(model);
}
TempData["SuccessMessage"] = "The article was validated and is ready to save.";
return RedirectToAction(nameof(Index));
}
[HttpGet]
public IActionResult Index()
{
return View();
}
}
After model binding completes, MVC evaluates the validation attributes and stores the results in ModelState. Do not save to the database when ModelState.IsValid is false. For additional rules discovered in the controller, use ModelState.AddModelError.
Redirecting after a successful POST follows the Post-Redirect-Get pattern. It prevents a browser refresh from submitting the same form again. When the POST is invalid, return the same View directly with the submitted ViewModel so that values and errors are preserved.
3. Displaying messages in a Razor View
Validation Tag Helpers use the validation metadata on the ViewModel and generate the appropriate HTML validation attributes. For each field, place a label, input, and validation message together.
@model CmsApp.ViewModels.ArticleCreateViewModel
New article
asp-validation-for displays a message for a particular property beside its input. asp-validation-summary="ModelOnly" displays errors that are not associated with a specific property. Use All when you want a summary containing both property and model-level errors.
When the View is rendered after an invalid POST, the Tag Helpers use the values in ModelState. This means the submitted value takes precedence over the ViewModel's initial value. Creating a new ViewModel before returning the View can accidentally discard the user's input and should be avoided.
4. Custom validation with IValidatableObject
Some rules depend on more than one property. For example, a scheduled article might need a reading time of at least two minutes, or an author email might be required to use a particular company domain. These model-level rules can be implemented with IValidatableObject.
using System.ComponentModel.DataAnnotations;
public class ArticleCreateViewModel : IValidatableObject
{
[Required(ErrorMessage = "The title is required.")]
[StringLength(120, MinimumLength = 5,
ErrorMessage = "The title must be between 5 and 120 characters.")]
public string Title { get; set; } = string.Empty;
[Required(ErrorMessage = "The summary is required.")]
[StringLength(300, MinimumLength = 20,
ErrorMessage = "The summary must be between 20 and 300 characters.")]
public string Summary { get; set; } = string.Empty;
[EmailAddress(ErrorMessage = "Enter a valid email address.")]
public string AuthorEmail { get; set; } = string.Empty;
[Range(1, 60, ErrorMessage = "Reading time must be between 1 and 60 minutes.")]
public int ReadingMinutes { get; set; }
public DateTime? PublishAt { get; set; }
public IEnumerable Validate(
ValidationContext validationContext)
{
if (PublishAt.HasValue && ReadingMinutes < 2)
{
yield return new ValidationResult(
"Scheduled articles must have a reading time of at least 2 minutes.",
new[] { nameof(ReadingMinutes), nameof(PublishAt) });
}
if (!string.IsNullOrWhiteSpace(AuthorEmail) &&
!AuthorEmail.EndsWith("@example.com", StringComparison.OrdinalIgnoreCase))
{
yield return new ValidationResult(
"The author email must use the example.com domain.",
new[] { nameof(AuthorEmail) });
}
}
}
When creating a ValidationResult, provide the related property names whenever possible. This allows the message to appear both in the summary and beside the relevant input. If no member name is supplied, the error may be treated only as a model-level message.
5. Writing a custom ValidationAttribute
If a rule will be reused across multiple ViewModels, a custom ValidationAttribute can be a better choice. For example, the following attribute ensures that a slug contains only lowercase letters, digits, and hyphens.
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
public sealed class SlugAttribute : ValidationAttribute
{
protected override ValidationResult? IsValid(
object? value,
ValidationContext validationContext)
{
var slug = value as string;
if (string.IsNullOrWhiteSpace(slug))
{
return ValidationResult.Success;
}
var isValid = Regex.IsMatch(slug, "^[a-z0-9]+(?:-[a-z0-9]+)*$");
return isValid
? ValidationResult.Success
: new ValidationResult(
"A slug may contain only lowercase letters, digits, and hyphens.");
}
}
You can apply this attribute to a property with [Slug]. Do not assume that custom attributes automatically run in the browser. Built-in Data Annotation rules may become HTML5 or jQuery Unobtrusive Validation attributes, while custom server rules must always be enforced on the server.
6. Combining client and server validation
Client-side validation requires the validation script partial included by the project template. For example, the following partial can be included in the layout or the relevant View:
@await Html.PartialAsync("_ValidationScriptsPartial")The Input Tag Helper can generate attributes such as data-val-required, data-val-length, and data-val-email from Data Annotation rules. With JavaScript enabled, the user receives immediate feedback before the form is submitted. However, a malicious client can disable these checks. Therefore, never remove the controller-side ModelState.IsValid check.
7. Accessible and clear messages
Validation messages should be actionable rather than technical. Instead of “Invalid value,” write something such as “Enter the email in the name@example.com format.” Tell the user what to change. Do not communicate errors through color alone; provide text as well. The label, input, and message should be associated with the same property.
- Render a visible
labelfor every input. - Place each message close to the input that caused the error.
- Use a summary for model-level errors or as additional navigation on long forms.
- Avoid language that blames the user.
- Use localized field names and messages in multilingual applications.
Common mistakes
- Trusting only client-side validation: Client scripts can be disabled, so server validation is mandatory.
- Redirecting after an invalid POST: A redirect can discard ModelState and submitted values. Return the same View with the model.
- Binding the entity directly: Properties that should not be editable may be posted accidentally. Use a dedicated ViewModel.
- Using the wrong ModelState key: If the key does not match a ViewModel property, the message will not appear beside the expected input.
- Scattering repeated business rules through controllers: Reusable rules belong in a custom attribute or a dedicated validation service.
- Writing vague or lengthy messages: Short messages that explain the correction provide a better experience.
Practice exercise
Create a CategoryCreateViewModel with name, slug, and description properties. The category name must be required and between 3 and 50 characters. The description is optional but must be shorter than 500 characters. Apply the custom SlugAttribute to the slug property. In the POST action, check whether the slug already exists and add a property error with ModelState.AddModelError(nameof(model.Slug), "This slug is already in use.") when a conflict is found. Display both property messages and the model summary in the View. Finally, disable JavaScript and verify that server-side validation still works.
Conclusion
In this lesson, we validated ASP.NET Core MVC forms with Data Annotations, IValidatableObject, custom validation attributes, and ModelState. Preserving submitted values, associating messages with the correct fields, and providing accessible feedback are important not only for correctness but also for a good user experience.
In the next stage, we will begin saving validated data to the database with Entity Framework Core. Keeping validation at the ViewModel boundary will help the database and application layers evolve in a clear and maintainable way.