Implementing Validation in Razor Pages
Validation is a crucial aspect of web development to ensure data integrity and provide a good user experience. ASP.NET Core Razor Pages offers robust support for validation, leveraging the same data annotation attributes and validation infrastructure as MVC.
Using Data Annotations
The most common and straightforward way to implement validation is by using data annotation attributes from the System.ComponentModel.DataAnnotations
namespace. These attributes can be applied directly to the properties of your Razor Page model (the `PageModel` class).
Common Validation Attributes:
[Required]
: Ensures a property is not empty.[StringLength(maxLength, MinimumLength = minLength)]
: Validates the length of a string.[RegularExpression(pattern)]
: Validates a string against a regular expression.[EmailAddress]
: Validates that a string is a valid email format.[Url]
: Validates that a string is a valid URL.[Range(minimum, maximum)]
: Validates that a numeric value is within a specified range.[Compare(otherProperty)]
: Compares a property with another property (e.g., for password confirmation).[Remote(action, controller)]
: Performs validation asynchronously on the server.
Example:
Consider a simple registration form. We can define the model like this:
using System.ComponentModel.DataAnnotations;
public class RegisterModel : PageModel
{
[Required(ErrorMessage = "Username is required.")]
[StringLength(50, MinimumLength = 3, ErrorMessage = "Username must be between 3 and 50 characters.")]
public string Username { get; set; }
[Required(ErrorMessage = "Email is required.")]
[EmailAddress(ErrorMessage = "Please enter a valid email address.")]
public string Email { get; set; }
[Required(ErrorMessage = "Password is required.")]
[StringLength(100, MinimumLength = 8, ErrorMessage = "Password must be at least 8 characters long.")]
[DataType(DataType.Password)]
public string Password { get; set; }
[Required(ErrorMessage = "Password confirmation is required.")]
[DataType(DataType.Password)]
[Compare(nameof(Password), ErrorMessage = "Passwords do not match.")]
public string ConfirmPassword { get; set; }
public void OnGet()
{
}
public IActionResult OnPost()
{
if (!ModelState.IsValid)
{
return Page(); // Redisplay the page with validation errors
}
// Process registration logic here
// ...
return RedirectToPage("./Success"); // Redirect on successful submission
}
}
Displaying Validation Errors in the View
In your Razor Page view (.cshtml
file), you can easily display validation error messages using the asp-validation-for
tag helper.
Example View (`Register.cshtml`):
@page
@model RegisterModel
@{
ViewData["Title"] = "Register";
}
Register New Account
@section Scripts {
}
<partial name="_ValidationScriptsPartial" />
in the Scripts
section includes the necessary jQuery Validate unobtrusive scripts for client-side validation. Ensure this partial view exists in your project (usually found in `Pages/Shared`).
Client-Side vs. Server-Side Validation
By default, ASP.NET Core Razor Pages provides both client-side (via JavaScript) and server-side validation.
- Client-side validation: Provides immediate feedback to the user as they fill out the form, improving usability.
- Server-side validation: Is essential as it runs on the server and cannot be bypassed by users. Always perform server-side validation to guarantee data integrity.
Custom Validation
For more complex validation scenarios that cannot be handled by built-in attributes, you can create custom validation attributes by inheriting from ValidationAttribute
or implement the IValidatableObject
interface on your model.
Using IValidatableObject
:
This is useful for cross-property validation.
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc.RazorPages;
public class ComplexModel : PageModel, IValidatableObject
{
[Required]
public string FieldA { get; set; }
[Required]
public string FieldB { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var errors = new List<ValidationResult>();
if (FieldA == "Error" && FieldB == "Trigger")
{
errors.Add(new ValidationResult("Combination of FieldA and FieldB is invalid.", new[] { nameof(FieldA), nameof(FieldB) }));
}
return errors;
}
public void OnGet() {}
public IActionResult OnPost()
{
if (!ModelState.IsValid)
{
return Page();
}
return RedirectToPage("./Success");
}
}
Validation Summary
You can display a summary of all validation errors using the asp-validation-summary
tag helper:
<div asp-validation-summary="All" class="text-danger"></div>
Setting asp-validation-summary
to "All"
will display all validation errors, including those related to the model itself and any model state errors.