ヘッダー
C# Sample Programs
 

Required Validation

01/05/2024

This article deals with ASP.NET Core Razor Pages.

 

All sample programs in this article are based on the Visual Studio Project template "ASP.NET Core Web App" and you must add the Razor pages in th Pages folder.

 

 

 

Display an error message for required input

In this sample, Entering nothing in the product name or price and click the submit button, an error message will be displayed.

RequiredValidation.cshtml.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace WorkStandard.Pages.validation
{
    public class RequiredValidationModel : PageModel
    {
        [BindProperty]
        [DisplayName("Product Name")]
        [Required(ErrorMessage = "{0} is required.")]
        public string? productName { get; set; }

        [BindProperty]
        [DisplayName("Price")]
        [Required(ErrorMessage = "Enter a number for {0}.")]
        public int price { get; set; }

        public void OnPost()
        {
            //Server side validation check
            if (!ModelState.IsValid)
            {
                return;
            }

            System.Diagnostics.Debug.WriteLine($"No errors.{productName} {price}");
        }
    }
}

Where Debug.WriteLine outputs to

 

RequiredValidation.cshtml

@page
@model WorkStandard.Pages.validation.RequiredValidationModel

<form method="post" >
    <div class="mb-3">
        <label asp-for="productName"></label>
        <input asp-for="productName" class="form-control" />
        <span asp-validation-for="productName" class="text-danger"></span>
    </div>
    <div class="mb-3">
        <label asp-for="price"></label>
        <input asp-for="price" class="form-control" />
        <span asp-validation-for="price" class="text-danger"></span>
    </div>
    <div>
        <input type="submit" class="btn btn-primary" />
    </div>
</form>

@section Scripts {
    @{
        //Enable client side validation.
        await Html.RenderPartialAsync("_ValidationScriptsPartial");
    }
}

Note: As in this example, you must check validation result at server side. Malicious users can easily bypass client side validation to attack the server.

The CSS classes...

  • mb-3 Set little margin at bottom.→ Spacing
  • form-control Make the input a Bootstrap look.→ Forms
  • text-danger The string become red to indicate danger.→ Theme colors
  • btn btn-primary Give the button a Bootstrap look to indicate that it's a key feature.→ Buttons

 


日本語版