我正在像这样使用 CustomValidationAttribute
[CustomValidation(typeof(MyValidator),"Validate",ErrorMessage = "Foo")]
我的验证器包含这段代码
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;
}
}
那么如何从自定义验证属性中获取错误消息呢?
我知道这是一篇有点旧的帖子,但我将为这个问题提供更好的答案。
提问者想要使用CustomValidationAttribute
并使用传递错误消息ErrorMessage
财产。
如果您希望静态方法使用您在装饰属性时提供的错误消息,那么您可以返回:
new ValidationResult(string.Empty)
or ValidationResult("")
or ValidationResult(null)
.
The CustomValidationAttribute
覆盖FormatErrorMessage
其基类并进行条件检查string.IsNullOrEmpty
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)