okinawa

IT勉強メモ

.net core 自作のバリデーション

  

モデルクラスに記述するバージョン

using System. Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
 
// IValidatableObject インター フェイス を 実装
public class Book : IValidatableObject {
 
public int Id {get; set;}
public string Cat {get; set;}
 
// 検証 ルール の 実体
public IEnumerable < ValidationResult > Validate( ValidationContext validationContext)
{ if( this.Cat != "猫") {
 
// モデル全体エラー
yield return new ValidationResult( "Catは猫です。");
 
// Catプロパティにエラー表示するならこう
yield return new ValidationResult( "Catは猫です。", new { "Cat" });
 
} } }
 

コントローラに記述するバージョン

・参考

ASP.NET Core: エラーメッセージ一覧のカスタマイズ

public IActionResult Edit(int id)
{
if (id != character.CharacterId)
{
// モデル全体エラー表示するならこう
ModelState.AddModelError(string.Empty, "IDが見つからないよ");
 
// Catプロパティにエラー表示するならこう
ModelState.AddModelError("Cat", "IDが見つからないよ");
return View();
}
}