如何自定义验证属性错误消息
本文关键字:错误 消息 属性 验证 自定义 | 更新日期: 2023-09-27 18:21:07
目前,我有一个名为ExistingFileName的自定义验证属性(如下),但我给了它显示的错误消息
protected override System.ComponentModel.DataAnnotations.ValidationResult IsValid(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext)
{
if (value!=null)
{
string fileName = value.ToString();
if (FileExists(fileName))
{
return new ValidationResult("Sorry but there is already an image with this name please rename your image");
}
else
{
return ValidationResult.Success;
}
}
else
{
return new ValidationResult("Please enter a name for your image");
}
}
我是这样实现的:
[ExistingFileName]
public string NameOfImage { get; set; }
我确信在设置如下属性时有一种方法可以定义错误消息:
[ExistingFileName(errormessage="Blah blah blah")]
public string NameOfImage { get; set; }
但我不确定怎么做?非常感谢您的任何帮助
不要使用预定义的字符串返回ValidationResult
,而是尝试使用ErrorMessage
属性或任何其他自定义属性。例如:
private const string DefaultFileNotFoundMessage =
"Sorry but there is already an image with this name please rename your image";
private const string DefaultErrorMessage =
"Please enter a name for your image";
public string FileNotFoundMessage { get; set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value!=null)
{
string fileName = value.ToString();
if (FileExists(fileName))
{
return new ValidationResult(FileNotFoundMessage ??
DefaultFileNotFoundMessage);
}
else
{
return ValidationResult.Success;
}
}
else
{
return new ValidationResult(ErrorMessage ??
DefaultErrorMessage);
}
}
在你的注释中:
[ExistingFileName(FileNotFoundMessage = "Uh oh! Not Found!")]
public string NameOfImage { get; set; }
如果您没有明确设置自定义消息,它将回退到自定义属性中的预定义常量。
您继承了ValidationAttribute
吗?
那么就不需要将它保存在一个单独的变量中。从ValidationAttribute
类继承时,所有错误消息代码都可用。
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class ExistingFileNameAttribute : ValidationAttribute
{
public string FileFoundMessage = "Sorry but there is already an image with this name please rename your image";
public ExistingFileNameAttribute()
: base("Please enter a name for your image")
{
}
public override ValidationResult IsValid(object value)
{
if (value!=null)
{
string fileName = value.ToString();
if (FileExists(fileName))
{
return new ValidationResult(FileFoundMessage);
}
else
{
return ValidationResult.Success;
}
}
else
{
return new ValidationResult(ErrorMessage);
}
}
}
现在您可以使用它来验证您的字段/属性
[ExistingFileName(ErrorMessage="Blah blah blah", FileFoundMessage = "Blah Bla")]
public string NameOfImage { get; set; }
如果你像下面这样使用它。
[ExistingFileName]
public string NameOfImage { get; set; }
然后,它将使用ExistingFileName
属性的构造函数中设置的默认错误消息
希望能有所帮助。