目前,我有一个名为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; }
如果您未明确设置自定义消息,它将回退到您的自定义属性中的预定义常量。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句