フォームの入力値をクラスのメンバプロパティに代入する場合に、
クラスに対して検証処理を実行する方法はこちらの記事を参照してください。
@page
@model RazorPagesValidation.Pages.CustomValidation01Model
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
}
<html>
<head></head>
<body>
<h2>入力内容のカスタム検証のデモ</h2>
<form method="post">
<input type="text" asp-for="inputText"/>
<input type="submit" value="Exec" />
</form>
<p>@Model.MessageText</p>
</body>
</html>
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace RazorPagesValidation.Pages
{
public class MyValueAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
string svalue = (string)value;
if (svalue == "Penguin" || svalue == "Duck")
{
return ValidationResult.Success;
}
else
{
return new ValidationResult("Invalid Value");
}
}
}
public class CustomValidation01Model : PageModel
{
[BindProperty]
[MyValueAttribute]
public string inputText { get; set; }
public string MessageText { get; set; }
public void OnGet()
{
}
public PageResult OnPost()
{
if (ModelState.IsValid == true)
{
MessageText = "処理は成功しました。";
return Page();
}
else
{
foreach (ModelStateEntry se in ModelState.Values)
{
foreach (ModelError me in se.Errors)
{
MessageText += me.ErrorMessage;
}
}
return Page();
}
}
}
}
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
var app = builder.Build();
app.UseStaticFiles();
app.UseRouting();
app.MapRazorPages();
app.Run();
ValidationAttribute
クラスを継承したカスタムの継承クラスを作成します。
今回は MyValueAttribute クラスとしています。IsValid
メソッドをオーバーライドし、検証する処理をメソッド内に実装します。
検証が正しかった場合は、ValidationResult.Success
を返し、
誤っていた場合は、ValidationResult
オブジェクトを返します。ValidationResult オブジェクトのコンストラクタの第一引数に、エラーとなるメッセージを与えます。value
変数に設定されます。public class MyValueAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
string svalue = (string)value;
if (svalue == "Penguin" || svalue == "Duck")
{
return ValidationResult.Success;
}
else
{
return new ValidationResult("Invalid Value");
}
}
}
[(ValidationAttributeを継承したカスタム検証クラス)]
の属性を記述します。
今回の例では、ValidationAttributeクラスを継承した、MyValueAttribute クラスを属性に記述します。 [BindProperty]
[MyValueAttribute]
public string inputText { get; set; }
ModelState.IsValid
プロパティの値を確認します。
true
であれば検証は成功し、処理を続行します。false
の場合は検証に失敗したことになるため、エラーメッセージを表示します。
エラーメッセージは、ModelState.Values
プロパティの Errors
プロパティにメッセージが設定されています。複数のエラーメッセージが
設定されている場合もあるため、Errors
プロパティの値をループ等で取得しページに出力します。public PageResult OnPost()
{
if (ModelState.IsValid == true)
{
MessageText = "処理は成功しました。";
return Page();
}
else
{
foreach (ModelStateEntry se in ModelState.Values)
{
foreach (ModelError me in se.Errors)
{
MessageText += me.ErrorMessage;
}
}
return Page();
}
}
(アプリケーションルートURL)/CustomValidation01
にアクセスします。下図のウィンドウが表示されます。Bear
を入力します。@page
@model RazorPagesValidation.Pages.CustomValidation02Model
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
}
<html>
<head></head>
<body>
<h2>入力内容のカスタム検証のデモ</h2>
<form method="post">
<input type="text" asp-for="inputText1"/><br />
<text>@Model.ErrorMessageText1</text><br/>
<input type="text" asp-for="inputText2"/><br />
<text>@Model.ErrorMessageText2</text><br/>
<input type="text" asp-for="inputText3"/><br />
<text>@Model.ErrorMessageText3</text><br/>
<input type="submit" value="Exec" />
</form>
<p>@Model.MessageText</p>
</body>
</html>
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace RazorPagesValidation.Pages
{
public class MyValue1Attribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
string svalue = (string)value;
if (svalue == "Penguin" || svalue == "Duck") {
return ValidationResult.Success;
}
else {
return new ValidationResult("Penguin か Duck のどちらかを入力してください。");
}
}
}
public class MyValue2Attribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
int ivalue;
if (int.TryParse((string)value, out ivalue) == true) {
return ValidationResult.Success;
}
else {
return new ValidationResult("数値を入力してください。");
}
}
}
public class MyValue3Attribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
string svalue = (string)value;
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("^[A-Z]$");
System.Text.RegularExpressions.Match match = reg.Match(svalue);
if (match.Success == true) {
return ValidationResult.Success;
}
else {
return new ValidationResult("AからZの大文字一文字を入力してください。");
}
}
}
public class CustomValidation02Model : PageModel
{
[BindProperty]
[MyValue1Attribute]
public string inputText1 { get; set; }
[BindProperty]
[MyValue2Attribute]
public string inputText2 { get; set; }
[BindProperty]
[MyValue3Attribute]
public string inputText3 { get; set; }
public string ErrorMessageText1 { get; set; }
public string ErrorMessageText2 { get; set; }
public string ErrorMessageText3 { get; set; }
public string MessageText { get; set; }
public void OnGet()
{
}
public PageResult OnPost()
{
if (ModelState.IsValid == true) {
MessageText = "処理は成功しました。";
}
else {
ErrorMessageText1 = "";
if (ViewData.ModelState["inputText1"] != null) {
ModelStateEntry mse = ViewData.ModelState["inputText1"]!;
foreach (ModelError me in mse.Errors) {
ErrorMessageText1 += me.ErrorMessage;
}
}
if (ViewData.ModelState["inputText2"] != null) {
ModelStateEntry mse = ViewData.ModelState["inputText2"]!;
ErrorMessageText2 = "";
foreach (ModelError me in mse.Errors) {
ErrorMessageText2 += me.ErrorMessage;
}
}
if (ViewData.ModelState["inputText3"] != null) {
ModelStateEntry mse = ViewData.ModelState["inputText3"]!;
ErrorMessageText3 = "";
foreach (ModelError me in mse.Errors) {
ErrorMessageText3 += me.ErrorMessage;
}
}
}
return Page();
}
}
}
[BindProperty]
[MyValue1Attribute]
public string inputText1 { get; set; }
[BindProperty]
[MyValue2Attribute]
public string inputText2 { get; set; }
[BindProperty]
[MyValue3Attribute]
public string inputText3 { get; set; }
public class MyValue1Attribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
string svalue = (string)value;
if (svalue == "Penguin" || svalue == "Duck") {
return ValidationResult.Success;
}
else {
return new ValidationResult("Penguin か Duck のどちらかを入力してください。");
}
}
}
public class MyValue2Attribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
int ivalue;
if (int.TryParse((string)value, out ivalue) == true) {
return ValidationResult.Success;
}
else {
return new ValidationResult("数値を入力してください。");
}
}
}
public class MyValue3Attribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
string svalue = (string)value;
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("^[A-Z]$");
System.Text.RegularExpressions.Match match = reg.Match(svalue);
if (match.Success == true) {
return ValidationResult.Success;
}
else {
return new ValidationResult("AからZの大文字一文字を入力してください。");
}
}
(アプリケーションルートURL)/CustomValidation02
のURLにアクセスします。
下図のページが表示されます。