MVC4 アプリケーション用のカスタム バリデータを構築しています。RequiredAttribute
物事をシンプルに保ち、この質問の目的に焦点を当てるために、クラスのサーバー側とクライアント側の検証を再実装しているとしましょう。
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class MyRequiredAttribute: ValidationAttribute, IClientValidatable
{
public MyRequiredAttribute() : base("The {0} field is required.")
{
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value == null)
{
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
return null;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRequiredRule(ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()));
}
}
これをテストするために、非常に単純なコントローラーがあります。
public class TestController : Controller
{
public ActionResult Index()
{
return View(new MyThing {Value = "whatever"});
}
[HttpPost]
public ActionResult Index(MyThing thing)
{
if (ModelState.IsValid)
{
return Content("Good choice!");
}
return View(thing);
}
}
そして非常に単純なモデル:
public class MyThing
{
[MyRequired]
public string Value { get; set; }
[Required]
public string OtherValue { get; set; }
}
そして最後にインデックス ビュー:
@model MyThing
@{
Layout = "~/Views/Shared/_LayoutWithAllTheAppropriateValidationScripts.cshtml";
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
@using(Html.BeginForm()){
@Html.ValidationSummary(true)
@Html.EditorForModel()
<input type="submit" value="submit"/>
}
</div>
</body>
</html>
Value
カスタムMyRequiredAttribute
でOtherValue
装飾されたものと標準で装飾されたものがあることに気付くでしょうRequiredAttribute
。
RequiredAttribute
これらは両方ともサーバー側で美しく機能し、ポストバックで適切な検証メッセージを返しますが、クライアント側で機能するのは標準のみです。カスタムプロパティで a のModelClientValidationRequiredRule
代わりに aを使用しているため、カスタムのクライアント側検証ルールを定義する必要はないと想定していますが、そこまで到達できていないため、確かなことはわかりません。デバッガーはメソッド内で中断することはなく、モデルのプロパティに対して生成された入力 html 要素には、フィールドのようにand属性がありません。これは、メソッドが実行する責任があると想定しています。ModelClientValidationRule
ValidationType
GetClientValidationRules
Value
data-val-required
data-val
OtherValue
GetClientValidationRules
ここで単純なものが欠けているに違いありません...それは何ですか?