【问题标题】:Get error message when using custom validation attribute使用自定义验证属性时收到错误消息
【发布时间】:2012-09-23 13:20:56
【问题描述】:

我正在使用这样的 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;
    }
}

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

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-3 data-annotations customvalidator


    【解决方案1】:

    我知道这是一个有点旧的帖子,但我会为这个问题提供更好的答案。

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

    如果您希望静态方法使用您在装饰属性时提供的错误消息,那么您可以返回:

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

    CustomValidationAttribute 覆盖其基类的FormatErrorMessage,并对string.IsNullOrEmpty 进行条件检查。

    【讨论】:

    • 谢谢。正是我想要的。
    【解决方案2】:

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

    [MyValidator(ErrorMessage = "Foo")]
    public TestProperty SomeProperty { get; set; }
    

    像这样:

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

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

    【讨论】:

    • 是的,有一种可靠的方法。要更好地回答所提出的实际问题,请参阅下面的答案。
    【解决方案3】:

    您可以查看以下帖子以获取有关如何做您想做的事情的一些想法(他们使用 JS):

    Custom validator error text through javascript?

    希望这会有所帮助。

    【讨论】:

      【解决方案4】:

      我发现可行的唯一方法是使用 TryValidateObject 从回发方法验证模型,如果失败,请再次显示模型 - 然后会出现错误。

          [HttpPost]
          public ActionResult Standard(Standard model)
          {
              var valContext = new ValidationContext(model, null, null);
              var valResults = new List<ValidationResult>();;
              bool b = Validator.TryValidateObject(model, valContext, valResults, true);
              if(!b)
                  return View(model);
              ...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-18
        • 2016-12-04
        • 1970-01-01
        相关资源
        最近更新 更多