目前我有一个名为 ExistingFileName 的自定义验证属性 (below) 但我已给它显示错误消息
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; }
如果您没有明确设置自定义消息,它将回退到自定义属性中的预定义常量。
关于c# - 如何自定义验证属性错误信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17474823/