ヘッダー
C# Sample Programs
 

Display error messages in one place

04/15/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 error messages in one place and error items in red

In this example, when you click the submit button, the error messages will be displayed at one place and error items will be in red.

 

ErrorSummary.cshtml.cs

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

namespace WorkStandard.Pages.validationlook
{
    public class ErrorSummaryModel : PageModel
    {
        [BindProperty]
        [DisplayName("Name")]
        [Required(ErrorMessage = "The {0} is required.")]
        public string? UserName { get; set; }

        [BindProperty]
        [DisplayName("Address")]
        [Required(ErrorMessage = "The {0} is required.")]
        public string? Address { get; set; }

        [BindProperty]
        [DisplayName("Telephone Number")]
        [DataType(DataType.PhoneNumber)]
        [Required(ErrorMessage = "The {0} is required.")]
        [StringLength(1000, MinimumLength = 3, ErrorMessage = "The {0} requires more than {2} characters.")]
        [RegularExpression("[0-9]*",ErrorMessage = "The {0} must be only numbers.")]
        public string? PhoneNumber { get; set; }

        public void OnPost()
        {
            if (!ModelState.IsValid)
            {
                return;
            }

            System.Diagnostics.Debug.WriteLine("No errors");
        }
    }
}

Where Debug.WriteLine appear

 

ErrorSummary.cshtml

@page
@model WorkStandard.Pages.validationlook.ErrorSummaryModel

<form method="post">
    <div asp-validation-summary="All" class="text-danger"></div>
    <div class="mb-3">
        <label asp-for="UserName"></label>
        <input asp-for="UserName" class="form-control" />
    </div>
    <div class="mb-3">
        <label asp-for="Address"></label>
        <input asp-for="Address" class="form-control" />
    </div>
    <div class="mb-3">
        <label asp-for="PhoneNumber"></label>
        <input asp-for="PhoneNumber" class="form-control" />
    </div>
    <div>
        <input type="submit" class="btn btn-primary" />
    </div>
</form>

@section Scripts
{
    <script>
        @* Turn error items red *@
        var umaUtil = umaUtil || {};
        umaUtil.TurnOnBootstrapError = function (doc) {
            const fields = doc.querySelectorAll('.input-validation-error');
            fields.forEach(field => {
                field.classList.add('is-invalid');
            });
        };
        umaUtil.TurnOnBootstrapError(document);
    </script>
}

Note: When combined with client-side validation, it may not work.

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

 

 

Display error messages in one place and append * by each error items

In this example, when you click the submit button, the error messages will be shown at one place and the labels next to error items will be appended red *.

 

ErrorSummaryAndIndicator.cshtml.cs

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

namespace WorkStandard.Pages.validationlook
{
    public class ErrorSummaryAndIndicatorModel : PageModel
    {
        [BindProperty]
        [DisplayName("Name")]
        [Required(ErrorMessage = "The {0} is required.")]
        public string? UserName { get; set; }

        [BindProperty]
        [DisplayName("Address")]
        [Required(ErrorMessage = "The {0} is required.")]
        public string? Address { get; set; }

        [BindProperty]
        [DisplayName("Telephone Number")]
        [DataType(DataType.PhoneNumber)]
        [Required(ErrorMessage = "The {0} is required.")]
        [StringLength(1000, MinimumLength = 3, ErrorMessage = "The {0} requires more than {2} characters.")]
        [RegularExpression("[0-9]*",ErrorMessage = "The {0} must be only numbers.")]
        public string? PhoneNumber { get; set; }

        public void OnPost()
        {
            if (!ModelState.IsValid)
            {
                return;
            }

            System.Diagnostics.Debug.WriteLine("No errors");
        }
    }
}

Where Debug.WriteLine appear

 

ErrorSummaryAndIndicator.cshtml

@page
@model WorkStandard.Pages.validationlook.ErrorSummaryAndIndicatorModel

<form method="post">
    <div asp-validation-summary="All" class="text-danger"></div>
    <div class="mb-3">
        <div>
            <label asp-for="UserName"></label>
            <span class="text-danger d-none fw-bold" asp-validation-for="UserName"></span>
        </div>
        <input asp-for="UserName" class="form-control" />
    </div>
    <div class="mb-3">
        <div>
            <label asp-for="Address"></label>
            <span class="text-danger d-none fw-bold" asp-validation-for="Address"></span>
        </div>
        <input asp-for="Address" class="form-control" />
    </div>
    <div class="mb-3">
        <div>
            <label asp-for="PhoneNumber"></label>
            <span class="text-danger d-none fw-bold" asp-validation-for="PhoneNumber"></span>
        </div>
        <input asp-for="PhoneNumber" class="form-control" />
    </div>
    <div>
        <input type="submit" class="btn btn-primary" />
    </div>
</form>

@section Scripts
{
    <script>
        @* Turn on visibility of span which is side by error item and has asp-validation-for. *@
        var umaUtil = umaUtil || {};
        umaUtil.TurnOnErrorIndicator = function (doc) {
            const fields = doc.querySelectorAll('.field-validation-error');
            fields.forEach(field => {
                field.classList.remove('d-none');
            });
        };
        umaUtil.TurnOnErrorIndicator(document);
    </script>
}

Note: When combined with client-side validation, it may not work.

Note: I have not been able to find any documentation that describes the behavior when setting characters in a span with asp-validation-for. So please be cautious if you use this method at important system.

The CSS classes...

  • mb-3 Set little margin at bottom.→ Spacing
  • d-none Hide the element. → Hiding elements
  • fw-bold Set text to bold. → Font weight and italics
  • 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

 

 

Display error messages all in one place and also display messages individually for error items

In this example, actualy not all error messages are in one place because the example uses client-side validation. When you turn off client-side validation, all error messages will be at on place completely. To turn off client-side validation, you have to remove the part of the source code with comment of "Enable client-side validtion" in cshtml in this example.

 

ErrorSummaryAndMessage.cshtml.cs

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

namespace WorkStandard.Pages.validationlook
{
    public class ErrorSummaryAndMessageModel : PageModel
    {
        [BindProperty]
        [DisplayName("Name")]
        [Required(ErrorMessage = "The {0} is required.")]
        public string? UserName { get; set; }

        [BindProperty]
        [DisplayName("Address")]
        [Required(ErrorMessage = "The {0} is required.")]
        public string? Address { get; set; }

        [BindProperty]
        [DisplayName("Telephone Number")]
        [DataType(DataType.PhoneNumber)]
        [Required(ErrorMessage = "The {0} is required.")]
        [StringLength(1000, MinimumLength = 3, ErrorMessage = "The {0} requires more than {2} characters.")]
        [RegularExpression("[0-9]*",ErrorMessage = "The {0} must be only numbers.")]
        public string? PhoneNumber { get; set; }

        public void OnPost()
        {
            if (!ModelState.IsValid)
            {
                return;
            }

            System.Diagnostics.Debug.WriteLine("No errors");
        }
    }
}

Where Debug.WriteLine appear

 

ErrorSummaryAndMessage.cshtml

@page
@model WorkStandard.Pages.validationlook.ErrorSummaryAndMessageModel

<form method="post">
    <div asp-validation-summary="All" class="text-danger"></div>
    <div class="mb-3">
        <label asp-for="UserName"></label>
        <input asp-for="UserName" class="form-control" />
        <span class="text-danger" asp-validation-for="UserName"></span>
    </div>
    <div class="mb-3">
        <label asp-for="Address"></label>
        <input asp-for="Address" class="form-control" />
        <span class="text-danger" asp-validation-for="Address"></span>
    </div>
    <div class="mb-3">
        <label asp-for="PhoneNumber"></label>
        <input asp-for="PhoneNumber" class="form-control" />
        <span class="text-danger" asp-validation-for="PhoneNumber"></span>
    </div>
    <div>
        <input type="submit" class="btn btn-primary" />
    </div>
</form>

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

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

 


日本語版