c# - 如何自定义验证属性错误信息?

标签 c# validation asp.net-mvc-4

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

相关文章:

c# - 当字符串中有反斜杠时,IndexOf 失败——为什么?

c# - Dynamics 365 - 使用 IOrganizationService 创建 OrganizationServiceProxy

c# - ^ 运算符是做什么的?

asp.net - ASP .net 验证技术

c# - ASP.NET MVC 4 RouteLink 不工作

c# - 将 int 转换为 boolean 值的更好方法

php - 使用ajax和laravel实时验证电子邮件(如果电子邮件已在数据库中,则显示电子邮件已被占用),就像gmail注册页面一样

java - 累积验证违规的设计模式

jquery - 如何查找 Jquery 是否在某处禁用 html 中的 anchor 标记

c# - 如何在 Asp.net MVC 中将两个文本框的值相乘