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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17474823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:35:09  来源:igfitidea点击:

How to customize validation attribute error message?

c#validationasp.net-mvc-4

提问by Srb1313711

At the moment I have a custom validation attribute called ExistingFileName (below)but i have given it error messages to display

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

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; }

But I'm not sure how? Any help is greatly appreciated

但我不确定如何?任何帮助是极大的赞赏

采纳答案by Simon Belanger

Instead of returning ValidationResultwith a predefined string, try using the ErrorMessageproperty, or any other custom properties. For example:

不要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);
    }
}

And in your annotation:

在您的注释中:

[ExistingFileName(FileNotFoundMessage = "Uh oh! Not Found!")]
public string NameOfImage { get; set; }

If you don't explicitely set a custom message, it will fallback to the predefined constant in your custom attribute.

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

回答by Amila

Have you inherited from ValidationAttribute?

你有继承ValidationAttribute吗?

then you don't need to keep it in a separate variable. All error message code is available when you inherit from ValidationAttributeclass.

那么你不需要将它保存在一个单独的变量中。从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);
        }
    }
}

Now you can use this to validate your fields/properties

现在您可以使用它来验证您的字段/属性

[ExistingFileName(ErrorMessage="Blah blah blah", FileFoundMessage = "Blah Bla")]
public string NameOfImage { get; set; }

and if you use it like below.

如果你像下面那样使用它。

[ExistingFileName]
public string NameOfImage { get; set; }

then, it will use the default error message set in the constructor of the ExistingFileNameattribute

然后,它将使用在ExistingFileName属性的构造函数中设置的默认错误消息

Hope that helps.

希望有帮助。