System.ComponentModel.DataAnnotations supplies attributes for declaring validation rules on ASP.NET Core model classes. Model binding detects those attributes and records failures in ModelState. section 3.2.9
A practical validation setup combines:
- Required attributes with custom messages for missing names, email addresses, phone numbers, and attendance choices. section 3.2.9
- EmailAddress on the email property to reject invalid email input. section 3.2.9
- A nullable bool for WillAttend, allowing null to distinguish no selection from true or false. section 3.2.9
- ModelState.IsValid in the POST action to save valid responses or redisplay the form with errors. section 3.2.9
Listing 3.17 Applying validation in the GuestResponse.cs file in the Models folder
using System.ComponentModel.DataAnnotations;
namespace PartyInvites.Models {
public class GuestResponse {
[Required(ErrorMessage = "Please enter your name")]
public string? Name { get; set; }
[Required(ErrorMessage = "Please enter your email address")]
[EmailAddress]
public string? Email { get; set; }
[Required(ErrorMessage = "Please enter your phone number")]
public string? Phone { get; set; }
[Required(ErrorMessage = "Please specify whether you'll attend")]
public bool? WillAttend { get; set; }
}
}
Inspect the GuestResponse model with its validation attributes and custom error messages. section 3.2.9
