Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

ASP.NET Core razor pages validation

Suggested Videos
Part 16 - File upload in asp.net core razor pages | Text | Slides
Part 17 - Handle multiple forms in asp.net core razor pages | Text | Slides
Part 18 - TempData in ASP.NET Core | Text | Slides

In this video we will discuss model validation in ASP.NET Core razor pages. Let's understand this with an example.


Razor pages model validation example

Consider the following Employee Edit Form

razor pages validation example


We want to make both Name and Email fields required. If the required values are not provided and the razor page is submitted we want to display required validation errors as shown below.

razor pages required validation example

To make a field, a required field, apply Required attribute on the corresponding property of the model class. 

Installing Microsoft.AspNetCore.Mvc.DataAnnotations NuGet package

Employee model class is in a separate class library project. Required attribute is in System.ComponentModel.DataAnnotations namespace. This namespace is in Microsoft.AspNetCore.Mvc.DataAnnotations NuGet package. Install it using NuGet package manager.

To get to the NuGet package manager, right click on the project name in Solution Explorer and select Manage NuGet Packages from the context menu.

nuget package manager in visual studio 2019

Make UI fields required in Razor Pages

We want to make both Name and Email fields required. So decorate both the properties with the Required attribute.

To make Name field a required field, apply Required attribute on the Name property of the Employee model class. Required attribute is in System.ComponentModel.DataAnnotations namespace.

public class Employee
{
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    [Required]
    public string Email { get; set; }
    public string PhotoPath getset; }
    public Dept Department { get; set; }
}

Razor page validation
  • When the Update button is clicked, the razor page is submitted
  • Model binding maps the posted form values to the respective properties of the Employee model class
  • With the Required attribute on the Name property of the Employee class, if a value for the Name property is not present, the validation fails
  • Use ModelState.IsValid property to check if validation has failed or succeeded
  • If validation has failed we return the same razor page so the user can provide the required data and resubmit the form
public IActionResult OnPost()
{
    if (ModelState.IsValid)
    {
        if (Photo != null)
        {
            if (Employee.PhotoPath != null)
            {
                string filePath = Path.Combine(webHostEnvironment.WebRootPath,
                    "images", Employee.PhotoPath);
                System.IO.File.Delete(filePath);
            }

            Employee.PhotoPath = ProcessUploadedFile();
        }

        Employee = employeeRepository.Update(Employee);
        return RedirectToPage("Index");
    }
    return Page();
}

Displaying validation errors in razor pages

To display validation errors use asp-validation-for and asp-validation-summary tag helpers. asp-validation-for tag helper displays a validation message for a single property of our model class. asp-validation-summary tag helper displays a summary of validation errors.

To display the validation error associated with the Name property of the Employee class use asp-validation-for tag helper on a <span> element as shown below.

<div class="form-group row">
    <label asp-for="Employee.NEmployeeame" class="col-sm-2 col-form-label"></label>
    <div class="col-sm-10">
        <input asp-for="Employee.Name" class="form-control" placeholder="Name">
        <span asp-validation-for="Employee.Name"></span>
    </div>
</div>

To display a summary of all validation errors use asp-validation-summary tag helper on a <div> element as shown below.

<div asp-validation-summary="All">
</div>

Custom validation error message in razor pages

public class Employee
{
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    public string Email { get; set; }
    public Dept Department { get; set; }
}

By default the Required attribute on the Name property displays the following validation error message.
The Name field is required.

If you want to change the validation error message to "Name is required" you can do so using the ErrorMessage property of the Required attribute as shown below.

public class Employee
{
    public int Id { get; set; }
    [Required(ErrorMessage = "Name is required")]
    public string Name { get; set; }
    public string Email { get; set; }
    public Dept Department { get; set; }
}

Built-in Model Validation Attributes in AP.NET Core

The following are some of the common built-in validation attributes in ASP.NET Core
Attribute Purpose
Required Specifies the field is required
Range Specifies the minimum and maximum value allowed
MinLength Specifies the minimum length of a string
MaxLength Specifies the maximum length of a string
Compare Compares 2 properties of a model. For example compare Email and ConfirmEmail properties
RegularExpression Validates if the provided value matches the pattern specified by the regular expression

Display Attribute

This is not a validation attribute. It is commonly used for display purpose in the UI. 

For example, in the UI by default, the label for Email field displays the text Email, because the property name is Email

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public Dept Department { get; set; }
}

If you want the label to display Office Email instead, use the Display attribute

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    [Display(Name = "Office Email")]
    public string Email { get; set; }
    public Dept Department { get; set; }
}

Using Multiple Model Validation Attributes

Multiple validation attributes can be applied on a property by separating them with a comma as shown on the Name property or we stack them on top of each other as shown on the Email property.

public class Employee
{
    public int Id { get; set; }
    [Required, MinLength(3, ErrorMessage = "Name must contain at least 50 characters")]
    public string Name { get; set; }
    [Display(Name = "Office Email")]
    [RegularExpression(@"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$",
        ErrorMessage = "Invalid email format")]
    [Required]
    public string Email { get; set; }
    public Dept Department { get; set; }
}

Model Validation Errors Colour

To change the colour of the model validation errors on the UI, use Bootstrap text-danger class on the <span> and <div> elements that have asp-validation-for and asp-validation-summary tag helpers

<div asp-validation-summary="All" class="text-danger"></div>
<span asp-validation-for="Name" class="text-danger"></span>

asp.net core tutorial for beginners

1 comment:

It would be great if you can help share these free resources