如何自定义validation属性错误信息?

目前我有一个名为ExistingFileName的自定义validation属性(下面),但我已经给它显示错误消息

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

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

你从ValidationAttributeinheritance了吗?

那么你不需要将它保存在一个单独的变量中。 从ValidationAttribute类inheritance时,所有错误消息代码都可用。

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

现在,您可以使用它来validation字段/属性

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

如果您使用它如下。

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

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

希望有所帮助。