いくつかの検索と試行錯誤の後、このブログ投稿に基づいたコードを使用しました。以下の適応コード。
プロジェクトに新しいクラスを追加します。
using System.Web.Mvc;
public class FixedRequiredAttributeAdapter : RequiredAttributeAdapter
{
public FixedRequiredAttributeAdapter (ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute)
: base(metadata, context, attribute)
{
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
// set the error message here or use a resource file
// access the original message with "ErrorMessage"
var errorMessage = "Required field!":
return new[] { new ModelClientValidationRequiredRule(errorMessage) };
}
}
app start in を変更して、このアダプターを使用するように MVC に指示しますglobal_asax
。
protected void Application_Start()
{
...
DataAnnotationsModelValidatorProvider.RegisterAdapterFactory(
typeof(RequiredAttribute),
(metadata, controllerContext, attribute) => new FixedRequiredAttributeAdapter(
metadata,
controllerContext,
(RequiredAttribute)attribute));
クラス/プロパティに基づいてリソース ファイルから取得するなど、エラー メッセージに対してできることは他にもあります。
var className = Metadata.ContainerType.Name;
var propertyName = Metadata.PropertyName;
var key = string.Format("{0}_{1}_required", className, propertyName);
MVC5 でテスト済み。
更新:これは、javascript/目立たない検証でのみ機能するようです。ポストバック検証を取得するために JavaScript をオフにしても、「{} フィールドは必須です」と表示されます。