一些搜索和反覆試驗之後,我使用了基於this blog post一些代碼。改編下面的代碼。
添加一個新類到您的項目:
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) };
}
}
告訴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以獲得回傳驗證,它仍會顯示「The {}」字段是必需的「。
看看這個http://stackoverflow.com/questions/6214066/how-to-change-default-validation-error-message-in-asp-net-mvc .. – user2232273
我試過在鏈接,我把「RequiredAttribute_ValidationError」和「PropertyValueRequired」鍵都放在資源文件中,但什麼都沒有發生。 –
請在查詢中粘貼您的模型/視圖/控制器 –