使用自定义验证属性时获取错误消息

Mar*_*cus 6 c# asp.net-mvc customvalidator data-annotations asp.net-mvc-3

我正在使用像这样的CustomValidationAttribute

[CustomValidation(typeof(MyValidator),"Validate",ErrorMessage = "Foo")]
Run Code Online (Sandbox Code Playgroud)

我的验证器包含此代码

public class MyValidator {
    public static ValidationResult Validate(TestProperty testProperty, ValidationContext validationContext) {
        if (string.IsNullOrEmpty(testProperty.Name)) {
            return new ValidationResult(""); <-- how can I get the error message  from the custom validation attribute? 
        }
        return ValidationResult.Success;
    }
}
Run Code Online (Sandbox Code Playgroud)

那么如何从自定义验证属性中获取错误消息?

Dar*_*rov 6

没有可靠的方法从属性中获取错误消息.或者,您可以编写自定义验证属性:

[MyValidator(ErrorMessage = "Foo")]
public TestProperty SomeProperty { get; set; }
Run Code Online (Sandbox Code Playgroud)

像这样:

public class MyValidatorAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var testProperty = (TestProperty)value;
        if (testProperty == null || string.IsNullOrEmpty(testProperty.Name))
        {
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
        }

        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,将从自定义验证属性推断出错误消息.


Kir*_*rby 5

我知道这是一个过时的帖子,但是我将为这个问题提供一个更好的答案。

询问者想要使用,CustomValidationAttribute并使用ErrorMessage属性传递错误消息。

如果您希望您的静态方法使用装饰属性时提供的错误消息,则返回以下两种方法之一:

new ValidationResult(string.Empty)ValidationResult("")ValidationResult(null)

CustomValidationAttribute覆盖了FormatErrorMessage其基类的和做的条件检查string.IsNullOrEmpty