using Microsoft.AspNetCore.Mvc.DataAnnotations; public class MyModel { [Required(ErrorMessage = "The Name field is required.")] public string Name { get; set; } } // In your controller action method public IActionResult MyActionMethod([FromBody]MyModel model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } // Rest of the code }
using System.ComponentModel.DataAnnotations; using Microsoft.AspNetCore.Mvc.DataAnnotations; public class MyModel { [RegularExpression(@"^\d{3}-\d{2}-\d{4}$", ErrorMessage = "The SSN field is not valid.")] public string SSN { get; set; } } // In Startup.cs file, inside ConfigureServices method public void ConfigureServices(IServiceCollection services) { services.AddControllers() .AddNewtonsoftJson() .AddDataAnnotationsLocalization(options => options.DataAnnotationLocalizerProvider = (type, factory) => factory.Create(typeof(SharedResource))); } // In SharedResource.cs file namespace MyApp.Resources { public class SharedResource { } }In example 1, we have added a required validation rule for the `Name` property. If the value for this property is null or empty when the model is being submitted, an error message will be added to the `ModelState` object, which we can later check in the controller action method. In example 2, we have added a regular expression validation rule for the `SSN` property. If the value for this property does not match the specified regular expression pattern, an error message will be added to the `ModelState` object. The package library for this is `Microsoft.AspNetCore.Mvc.Core`.