如何自定义验证属性错误消息?

24

目前我有一个名为 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; }

但我不确定怎么做?非常感谢任何帮助。

2个回答

34

不要返回预定义字符串的 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; }

如果您没有显式设置自定义消息,它将回退到您自定义属性中预定义的常量。

12

你是否继承自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属性构造函数中设置的默认错误消息。

希望这可以帮到你。


你的 IsValid 应该返回一个布尔值,但你却返回了一个 ValidationResult。这样正确吗?我无法让它工作,并且我无法重写 IsValid 以返回一个 ValidationResult - muttley91
感谢指出,返回类型必须是ValidationResult。 - Amila
@muttley91 同样的问题,我只能返回布尔值 :'( - J4N
2
重写方法为protected override ValidationResult IsValid(object value, ValidationContext validationContext)。应返回ValidationResult.Success而不是true,应返回new ValidationResult("My custom error message")而不是false - jhhwilliams

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接