更新时间:2022-10-23 17:34:23
您可以创建自定义 ValidationAttribute
扩展 RequiredAttribute标签
,并设置在那里的值。是这样的:
公共类MyRequiredAttribute:RequiredAttribute标签
{
公共MyRequiredAttribute()
{
ErrorMessageResourceType = typeof运算(Resources.ValidationErrors);
ErrorMessageResourceName =必需;
}
}
然后用自定义属性装饰你的模型。
默认消息被编译成汇编DataAnnotations在资源文件在 System.ComponentModel.DataAnnotations.Resources.DataAnnotationsResources.resources
是 RequiredAttribute_ValidationError = {0}字段是必需的。
。因此,要回答你的问题,是的,这消息DataAnnotations的一部分。
编辑: PropertyValueRequired
用于非可空类型的空值的错误。如下 PropertyValueInvalid
提到的用于类型转换错误。
Good day!
I've the following ViewModel class I use for login form:
using System.ComponentModel.DataAnnotations;
...
public class UserLogin : IDataErrorInfo
{
[Required]
[DisplayName("Login")]
public string Login { get; set; }
[Required]
[DisplayName("Password")]
public string Password { get; set; }
[DisplayName("Remember Me")]
public bool RememberMe { get; set; }
#region IDataErrorInfo Members
// This will be a Model-level error
public string Error
{
get
{
if (!WebUser.CanLogin(Login, Password))
{
return Resources.ValidationErrors.InvalidLoginPassword;
}
else
{
return String.Empty;
}
}
}
// All is handled by DataAnnotation attributes, just a stub for interface
public string this[string columnName]
{
get
{
return string.Empty;
}
}
#endregion
}
And this in Global.asax
:
DefaultModelBinder.ResourceClassKey = "BinderMessages";
ValidationExtensions.ResourceClassKey = "BinderMessages";
The resource file BinderMessages.resx
is placed inside App_GlobalResources it has two keys InvalidPropertyValue
(which works) and PropertyValueRequired
which doesn't and gives me default message.
Question: Is it possible to modify this message, or it's tied to DataAnnotations?
I've found many posts about this, but without solution. For now I just fallback to this:
[Required(ErrorMessageResourceType = typeof(Resources.ValidationErrors), ErrorMessageResourceName = "Required")]
You can create a custom ValidationAttribute
that extends RequiredAttribute
and sets the values there. Something like:
public class MyRequiredAttribute : RequiredAttribute
{
public MyRequiredAttribute()
{
ErrorMessageResourceType = typeof(Resources.ValidationErrors);
ErrorMessageResourceName = "Required";
}
}
Then decorate your Model with your custom attribute.
The default message is compiled into the DataAnnotations assembly in the resource file under System.ComponentModel.DataAnnotations.Resources.DataAnnotationsResources.resources
and is RequiredAttribute_ValidationError=The {0} field is required.
. So to answer your question, yes, that message is part of DataAnnotations.
Edit: PropertyValueRequired
is used for errors on null values with non-nullable types. As mentioned below PropertyValueInvalid
is used for type conversion errors.