`Required` is a validation attribute from `System.ComponentModel.DataAnnotations`. Put `[Required]` on a model property when a request must supply a value. ASP.NET Core checks the rule during model binding, before the action runs. Keeping the rule on the model lets multiple forms or actions use the same constraint instead of repeating checks. section 3.2.9 section 29.5
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; }
}
}
The RSVP model marks name, email, phone, and attendance as required and gives each missing value a specific error message. `Email` also has a separate `[EmailAddress]` rule. section 3.2.9
Property types matter. With `bool? WillAttend`, an unanswered choice remains `null`, so `[Required]` can reject it. A non-nullable `bool` would be either `true` or `false`, hiding whether the user made a choice. For numeric properties that default to zero when omitted, use a rule such as `[Range]` to reject that default. ASP.NET Core can infer a required constraint from C#'s `required` keyword, but an explicit attribute makes the intent visible and can set `ErrorMessage`. section 3.2.9 section 19.5.4 section 29.5
Check `ModelState.IsValid` before using bound data. In a form action, an invalid model can return the form so a validation summary displays the errors; a valid RSVP can be stored and shown a thank-you view. In a JSON API action, invalid data can instead produce `BadRequest(ModelState)`, while valid data proceeds to storage. Required-field checks can coexist with other property rules and later model-level validation. section 3.2.9 section 19.5.4 section 29.5
Listing 19.25 Validation in the ProductsController.cs file in the Controllers folder
...
[HttpPost]
public async Task<IActionResult>
SaveProduct([FromBody] ProductBindingTarget target) {
if (ModelState.IsValid) {
Product p = target.ToProduct();
await context.Products.AddAsync(p);
await context.SaveChangesAsync();
return Ok(p);
}
return BadRequest(ModelState);
}
...
The POST action checks `ModelState.IsValid` before converting and saving a bound product; otherwise it returns the validation errors in a bad-request response. section 19.5.4
