问题描述
目前,我有一个名为ExistingFileName的自定义验证属性的(下同)的但我已经给它的错误消息显示
At the moment I have a custom validation attribute called ExistingFileName (below) but i have given it error messages to display
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");
}
}
我已经实现了它,像这样:
I have implemented it like so:
[ExistingFileName]
public string NameOfImage { get; set; }
我敢肯定,一个孤单的方式来定义设置像下面的属性时,错误消息:
Im sure theres a way to define the error message when setting the attribute like below:
[ExistingFileName(errormessage="Blah blah blah")]
public string NameOfImage { get; set; }
但我不知道怎么办?任何帮助是极大AP preciated
But I'm not sure how? Any help is greatly appreciated
推荐答案
为ValidationResult
以predefined字符串,请尝试使用的ErrorMessage
财产,或任何其他自定义属性。例如:
Instead of returning ValidationResult
with a predefined string, try using the ErrorMessage
property, or any other custom properties. For example:
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; }
如果你不明确地设置自定义消息,它会回退到predefined在自定义属性不变。
If you don't explicitely set a custom message, it will fallback to the predefined constant in your custom attribute.
这篇关于如何自定义的验证属性错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!