ヘッダー
C# Sample Programs
 

Validate if input values are equal

04/17/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.

 

 

Compare email address and confirmation email address

SameValueValidation.cshtml.cs

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

namespace WorkStandard.Pages.validation
{
    public class SameValueValidationModel : PageModel
    {
        [BindProperty]
        [DisplayName("email address")]
        [DataType(DataType.EmailAddress)]
        [Required(ErrorMessage = "The {0} is required.")]
        [Display(Name = "email address")] //This is the {1} of ErrorMessage of Compare
        public string? MailAddress { get; set; }

        [BindProperty]
        [DisplayName("confirmation email address")]
        [DataType(DataType.EmailAddress)]
        [Required(ErrorMessage = "The {0} is required.")]
        [Compare(nameof(MailAddress),ErrorMessage = "Not equals to {1}.")]
        public string? ConfirmMailAddress { get; set; }

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

            System.Diagnostics.Debug.WriteLine($"No errors. {MailAddress} {ConfirmMailAddress}");
        }
    }
}

Where Debug.WriteLine outputs to

 

SameValueValidation.cshtml

@page
@model WorkStandard.Pages.validation.SameValueValidationModel

<form method="post">
    <div class="mb-3">
        <label asp-for="MailAddress"></label>
        <input asp-for="MailAddress" class="form-control" />
        <span asp-validation-for="MailAddress" class="text-danger"></span>
    </div>
    <div class="mb-3">
        <label asp-for="ConfirmMailAddress"></label>
        <div class="form-text">For confirmation, please enter same email address above.</div>
        <input asp-for="ConfirmMailAddress" class="form-control" />
        <span asp-validation-for="ConfirmMailAddress" class="text-danger"></span>
    </div>
    <div>
        <input type="submit" class="btn btn-primary" />
    </div>
</form>

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
  • form-text Give the text a Bootstrap look for form item description.→ Form Text
  • btn btn-primary Give the button a Bootstrap look to indicate that it's a key feature.→ Buttons

 


日本語版