我遇到自定义DataAnnotation的问题。
public class RequiredInt32 : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
if (Convert.ToInt32(value) == 0)
{
return new ValidationResult("custom-message");
}
}
return ValidationResult.Success;
}
}
我有那个代码。如果符合条件,则不返回“custom-message”,则返回“字段无效”。对我来说,返回我想要的消息,我需要明确地说明。
[RequiredInt32(ErrorMessage = @“custom-message”)]
我有什么问题,如何获得默认信息。谢谢!
答案 0 :(得分:0)
如果您打算自定义格式错误消息,可以定义如下属性:
public class RequiredInt32 : ValidationAttribute
{
private const string _customFormat = "{0} is not valid";
private string _fieldName;
public RequiredInt32(string fieldName)
: base(_customFormat)
{
_fieldName = fieldName;
}
public override string FormatErrorMessage(string name)
{
return string.Format(ErrorMessageString, name);
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
if (Convert.ToInt32(value) == 0)
{
return new ValidationResult(FormatErrorMessage(_fieldName));
}
}
return ValidationResult.Success;
}
}
用法:
[RequiredInt32("MyField")]
public int NumberProperty {get;set;}