Implementing form validation using data annotations in ASP .NET 8 is a straightforward process that involves decorating your model classes with validation attributes and ensuring the validation logic is processed on the server side. Here’s a step-by-step guide to achieve this:
Step 1: Define Your Model with Data Annotations
Create the Model:
- Use data annotation attributes to specify validation rules.
csharpusing System.ComponentModel.DataAnnotations; public class User { [Required(ErrorMessage = "Name is required")] [StringLength(100, ErrorMessage = "Name cannot be longer than 100 characters")] public string Name { get; set; } [Required(ErrorMessage = "Email is required")] [EmailAddress(ErrorMessage = "Invalid email address")] public string Email { get; set; } [Required(ErrorMessage = "Age is required")] [Range(18, 100, ErrorMessage = "Age must be between 18 and 100")] public int Age { get; set; } }
Step 2: Create a Razor Page or MVC View
Create the Page Model:
- In Razor Pages, create a page model class that binds the
User
model.
csharpusing Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; public class RegisterModel : PageModel { [BindProperty] public User User { get; set; } public void OnGet() { // Initialize any data if needed } public IActionResult OnPost() { if (!ModelState.IsValid) { // Return the page with validation errors return Page(); } // Process the valid form data return RedirectToPage("Success"); } }
- In Razor Pages, create a page model class that binds the
Create the Razor Page:
- Create a Razor Page view file (
.cshtml
) to display the form and validation messages.
html@page @model YourNamespace.Pages.RegisterModel @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers <h2>Register</h2> <form method="post"> <div> <label asp-for="User.Name"></label> <input asp-for="User.Name" class="form-control" /> <span asp-validation-for="User.Name" class="text-danger"></span> </div> <div> <label asp-for="User.Email"></label> <input asp-for="User.Email" class="form-control" /> <span asp-validation-for="User.Email" class="text-danger"></span> </div> <div> <label asp-for="User.Age"></label> <input asp-for="User.Age" class="form-control" /> <span asp-validation-for="User.Age" class="text-danger"></span> </div> <button type="submit">Submit</button> </form> @section Scripts { <partial name="_ValidationScriptsPartial" /> }
- Create a Razor Page view file (
Step 3: Enable Client-Side Validation
Include Validation Scripts:
- Ensure that the validation scripts are included in your layout or page. In Razor Pages, this can be done by including
_ValidationScriptsPartial
.
html<!-- Views/Shared/_ValidationScriptsPartial.cshtml --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.11/jquery.validate.unobtrusive.min.js"></script>
- Ensure that the validation scripts are included in your layout or page. In Razor Pages, this can be done by including
Step 4: Handle Validation in the Controller (For MVC)
Create the Controller:
- In MVC, you would use a controller to handle the form submission and validation logic.
csharpusing Microsoft.AspNetCore.Mvc; public class AccountController : Controller { [HttpGet] public IActionResult Register() { return View(); } [HttpPost] public IActionResult Register(User user) { if (!ModelState.IsValid) { // Return the view with validation errors return View(user); } // Process the valid form data return RedirectToAction("Success"); } }
Create the View:
- Create a Razor view file for the form.
html<!-- Views/Account/Register.cshtml --> @model YourNamespace.Models.User @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers <h2>Register</h2> <form asp-action="Register" method="post"> <div> <label asp-for="Name"></label> <input asp-for="Name" class="form-control" /> <span asp-validation-for="Name" class="text-danger"></span> </div> <div> <label asp-for="Email"></label> <input asp-for="Email" class="form-control" /> <span asp-validation-for="Email" class="text-danger"></span> </div> <div> <label asp-for="Age"></label> <input asp-for="Age" class="form-control" /> <span asp-validation-for="Age" class="text-danger"></span> </div> <button type="submit">Submit</button> </form> @section Scripts { <partial name="_ValidationScriptsPartial" /> }
Summary
- Model with Data Annotations: Decorate your model properties with data annotations for validation.
- Razor Page or MVC View: Create a form in a Razor Page or MVC view using Tag Helpers.
- Validation Scripts: Include jQuery and validation scripts for client-side validation.
- Page Model or Controller: Handle form submission and validation in the Page Model (for Razor Pages) or Controller (for MVC).
By following these steps, you can implement robust form validation using data annotations in ASP .NET 8, ensuring both client-side and server-side validation for your web applications.