MVC:デフォルトのValidationMessageをオーバーライドする
-
05-07-2019 - |
質問
MVCの世界では、このビューモデルを使用しています...
public class MyViewModel{
[Required]
public string FirstName{ get; set; } }
...そして私の見解ではこの種のこと...
<%= Html.ValidationSummary("Please correct the errors and try again.") %>
<%= Html.TextBox("FirstName") %>
<%= Html.ValidationMessage("FirstName", "*") %>
質問:名前を指定せずにこのフォームを送信すると、次のメッセージが表示されます&quot; The FirstName field is required&quot;
OK。だから、私は自分の財産を...に変更します...
[DisplayName("First Name")]
[Required]
public string FirstName{ get; set; }
.. andになります&quot;「名」フィールドが必要です」
これまでのところすべて良い。
エラーメッセージに「First Name Blah Blah」と表示するようになりました。デフォルトメッセージをオーバーライドしてDisplayName +&quot;を表示するにはどうすればよいですか。 Blah Blah&quot ;、すべてのプロパティに
などの注釈を付けない[Required(ErrorMessage = "First Name Blah Blah")]
乾杯、
ETFairfax
解決
public class GenericRequired: RequiredAttribute
{
public GenericRequired()
{
this.ErrorMessage = "{0} Blah blah";
}
}
他のヒント
RequiredAttribute
をサブクラス化せずにこれを行う方法を次に示します。いくつかの属性アダプタークラスを作成するだけです。ここでは ErrorMessageResourceType
/ ErrorMessageResourceName
(リソースを使用)を使用していますが、 ErrorMessage
を簡単に設定したり、上書きの前に確認することもできます。これらを設定します。
Global.asax.cs:
public class MvcApplication : HttpApplication {
protected void Application_Start() {
// other stuff here ...
DataAnnotationsModelValidatorProvider.RegisterAdapter(
typeof(RequiredAttribute), typeof(CustomRequiredAttributeAdapter));
DataAnnotationsModelValidatorProvider.RegisterAdapter(
typeof(StringLengthAttribute), typeof(CustomStringLengthAttributeAdapter));
}
}
private class CustomRequiredAttributeAdapter : RequiredAttributeAdapter {
public CustomRequiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute)
: base(metadata, context, attribute)
{
attribute.ErrorMessageResourceType = typeof(Resources);
attribute.ErrorMessageResourceName = "ValRequired";
}
}
private class CustomStringLengthAttributeAdapter : StringLengthAttributeAdapter {
public CustomStringLengthAttributeAdapter(ModelMetadata metadata, ControllerContext context, StringLengthAttribute attribute)
: base(metadata, context, attribute)
{
attribute.ErrorMessageResourceType = typeof(Resources);
attribute.ErrorMessageResourceName = "ValStringLength";
}
}
この例では、Resources.resxという名前のリソースファイルを作成し、 ValRequired
を新しい必須のデフォルトメッセージとして、 ValStringLength
を文字列の長さがデフォルトメッセージを超えました。両方について、 {0}
はフィールドの名前を受け取ります。これは [Display(Name =&quot; Field Name&quot;)]
で設定できます。
RequiredAttributeはIClientValidatableを実装していないようです。したがって、RequiredAttributeをオーバーライドすると、クライアント側の検証が中断されます。
これは私がやったことであり、動作します。これが誰かの助けになることを願っています。
public class CustomRequiredAttribute : RequiredAttribute, IClientValidatable
{
public CustomRequiredAttribute()
{
this.ErrorMessage = "whatever your error message is";
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = this.ErrorMessage,
ValidationType = "required"
};
}
}
変更するだけ
[Required]
to
[Required(ErrorMessage = "Your Message, Bla bla bla aaa!")]
編集:[Required]属性を持つこのソリューションを探していて、それを見つけるのに問題があったため、これを投稿しました。この質問は既に存在するため、新しいQ / Aを作成してもあまり良くありません。
同じことを解決しようとしていて、MVC 4で非常に簡単な解決策を見つけました。
最初に、おそらくどこかにエラーメッセージを保存する必要があります。 http://afana.me/post/aspnet-mvcで詳しく説明されているカスタムリソースを使用しました。 -internationalization.aspx 。
重要なのは、 ResourcesProject.Resources.SomeCustomError または ResourcesProject.Resources.MainPageTitle などを呼び出すだけで、リソース(エラーメッセージも含む)を取得できることです。 Resourcesクラスにアクセスするには、現在のスレッドからカルチャ情報を取得し、適切な言語を返します。
ResourcesProject.Resources.RequiredAttribute にフィールド検証のエラーメッセージがあります。このメッセージをビューに表示するように設定するには、これらの2つのパラメーターで[必須]属性を更新するだけです。
ErrorMessageResourceType -呼び出されるタイプ(この例ではResourcesProject.Resources)
ErrorMessageResourceName -上記のタイプで呼び出されるプロパティ(この例ではRequiredAttribute)
これは、ユーザー名検証メッセージのみを表示する非常に単純化されたログインモデルです。フィールドが空の場合、 ResourcesProject.Resources.RequiredAttribute から文字列を取得し、エラーとして表示します。
public class LoginModel
{
[Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName="RequiredAttribute")]
[Display(Name = "User name")]
public string UserName { get; set; }
}
独自の属性を記述できます:
public class MyRequiredAttribute : ValidationAttribute
{
MyRequiredAttribute() : base(() => "{0} blah blah blah blaaaaaah")
{
}
public override bool IsValid(object value)
{
if (value == null)
{
return false;
}
string str = value as string;
if (str != null)
{
return (str.Trim().Length != 0);
}
return true;
}
}
これは、エラーメッセージが変更されたReflectorのRequiredAttributeのコピーです。
using Resources;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Web;
using System.Web.Mvc;
public class CustomRequiredAttribute : RequiredAttribute, IClientValidatable
{
public CustomRequiredAttribute()
{
ErrorMessageResourceType = typeof(ValidationResource);
ErrorMessageResourceName = "RequiredErrorMessage";
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = GetRequiredMessage(metadata.DisplayName),
ValidationType = "required"
};
}
private string GetRequiredMessage(string displayName) {
return displayName + " " + Resources.ValidationResource.RequiredErrorMessageClient;
}
}
App_GlobalResources / ValidationResource.resx
データアノテーションを使用する
[CustomRequired]
これは私のために働いた。コード内のコメントを注意深く読んでください。 (チャドの答えに基づく)。
// Keep the name the same as the original, it helps trigger the original javascript
// function for client side validation.
public class RequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute, IClientValidatable
{
public RequiredAttribute()
{
this.ErrorMessage = "Message" // doesnt get called again. only once.
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = "Message", // this gets called on every request, so it's contents can be dynamic.
ValidationType = "required"
};
}
}