ASP.NET Core MVC Validation

This document provides a comprehensive guide to implementing validation in ASP.NET Core MVC applications. Effective validation is crucial for ensuring data integrity, security, and a positive user experience.

Introduction to Validation

Validation is the process of ensuring that user input meets certain criteria before it is processed or saved. In ASP.NET Core MVC, validation can be implemented at various levels:

Implementing Validation with Data Annotations

The most common and recommended approach for validation in ASP.NET Core MVC is by using Data Annotations. These are attributes that you apply to your model properties.

Common Validation Attributes

Attribute Description Example
[Required] Ensures a property is not null or empty. [Required]
public string UserName { get; set; }
[StringLength(int max, int min = 0)] Validates the length of a string. [StringLength(50, MinimumLength = 3)]
public string Password { get; set; }
[EmailAddress] Validates that a string is in a valid email format. [EmailAddress]
public string Email { get; set; }
[RegularExpression(string pattern)] Validates a string against a regular expression. [RegularExpression(@"^\d+$")]
public string PostalCode { get; set; }
[Range(int min, int max)] Validates that a numeric value is within a specified range. [Range(1, 100)]
public int Age { get; set; }
[Compare(string otherProperty)] Compares two properties, often used for password confirmation. [Compare("Password")]
public string ConfirmPassword { get; set; }

Custom Validation Attributes

For more complex validation scenarios, you can create custom validation attributes by inheriting from ValidationAttribute.

Tip: You can also implement IValidatableObject directly on your model for model-level validation logic.
public class CustomValidationAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        // Your custom validation logic here
        // Return true if valid, false otherwise
        return value != null;
    }
}

Performing Validation in the Controller

ASP.NET Core MVC automatically handles the validation of your model when it is bound from the request. You can check the validity of the model within your controller actions using the ModelState property.

[HttpPost]
public IActionResult Create(MyViewModel model)
{
    if (ModelState.IsValid)
    {
        // Model is valid, proceed with saving or further processing
        return RedirectToAction("Success");
    }
    else
    {
        // Model is invalid, return the view with validation errors
        return View(model);
    }
}

Displaying Validation Errors in the View

Razor views provide helpers to display validation messages. Use the <validation-summary> tag helper to display a summary of all errors, and <span asp-validation-for="..."> for individual field errors.

@model MyViewModel

<form asp-action="Create" method="post">
    <div asp-validation-summary="ModelOnly" class="text-danger">
        <!-- Validation summary will be rendered here -->
    </div>

    <div class="form-group">
        <label asp-for="UserName">
        <input asp-for="UserName" class="form-control" />
        <span asp-validation-for="UserName" class="text-danger">
    </div>

    <div class="form-group">
        <label asp-for="Email">
        <input asp-for="Email" class="form-control" />
        <span asp-validation-for="Email" class="text-danger">
    </div>

    <button type="submit" class="btn btn-primary">Submit
</form>

@section Scripts {
    <script src="~/lib/jquery-validation/dist/jquery.validate.min.js">
    <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js">
}
Note: Ensure that you have included the necessary JavaScript validation libraries (jquery-validation and jquery-validation-unobtrusive) in your project and referenced them in your layout or view.

Client-Side Validation

By default, ASP.NET Core MVC leverages the unobtrusive JavaScript validation providers for client-side validation. When using Data Annotations and the appropriate tag helpers, client-side validation is automatically enabled, provided the required JavaScript files are included in your project.

Customizing Validation Messages

You can customize the default validation messages by using the ErrorMessage property of the validation attributes or by using resource files for localization.

[Required(ErrorMessage = "User name is required.")]
public string UserName { get; set; }

Advanced Validation Scenarios

Remote Validation

For validation that requires checking against external data (e.g., checking if a username already exists), you can use the [Remote] attribute.

[Remote(action: "VerifyUserName", controller: "Account")]
public string UserName { get; set; }

This will trigger an AJAX call to the specified action on the server to perform the validation.

Validation Summary Options

The asp-validation-summary tag helper has several options:

By effectively implementing and displaying validation, you can build more robust and user-friendly ASP.NET Core MVC applications.