【问题标题】:Custom Validation Attribute ASP.NET MVC自定义验证属性 ASP.NET MVC
【发布时间】:2011-03-30 07:06:37
【问题描述】:

在 ASP.NET MVC 中是否可以仅当不同的 CustomValidationAttribute 验证不同的字段时才执行一个字段上的 CustomValidationAttribute。

我的视图需要包含单独的日期和时间字段。我对两者都有单独的自定义验证属性。但是是否有可能只有当日期验证属性验证为真时才检查时间验证属性?

谢谢。

【问题讨论】:

  • 你为什么要这样做?如果日期和时间都无效,为什么不这样说呢?或者为什么不使用客户端验证来执行此操作,这将满足您的需求?

标签: asp.net-mvc


【解决方案1】:

检查时间验证属性 仅当日期验证属性 验证为真?

此语句表示自定义验证。是的,你可以这样做。您可以定义将其他字段的名称作为参数的自定义验证属性。然后,在重写的 Validate() 方法中,您可以通过名称获取该其他字段的 PropertyInfo,然后获取验证属性并验证它们。得到结果后,您可以决定是否对第一个字段进行验证。 Brad Wilson 在 mvcConf 上有很棒的关于验证的帖子

顺便说一句,你也可以实现 IClientValidatable 来完成客户端验证

这是非常非常的示例代码,它需要一些参数检查和错误处理等。但我认为想法很清楚

 public class OtherFieldDependentCustomValidationAttribute : ValidationAttribute
{
    public readonly string _fieldName;

    public OtherFieldDependentCustomValidationAttribute(string otherFieldName)
    {
        _fieldName = otherFieldName;
    }

    protected override System.ComponentModel.DataAnnotations.ValidationResult IsValid(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext)
    {
        //Get PropertyInfo For The Other Field
        PropertyInfo otherProperty = validationContext.ObjectType.GetProperty(_fieldName);

        //Get ValidationAttribute of that property. the OtherFieldDependentCustomValidationAttribute is sample, it can be replaced by other validation attribute
        OtherFieldDependentCustomValidationAttribute attribute = (OtherFieldDependentCustomValidationAttribute)(otherProperty.GetCustomAttributes(typeof(OtherFieldDependentCustomValidationAttribute), false))[0];

        if (attribute.IsValid(otherProperty.GetValue(validationContext.ObjectInstance, null), validationContext) == ValidationResult.Success)
        {
            //Other Field Is valid, do some custom validation on current field

            //custom validation....

            throw new ValidationException("Other is valid, but this is not");
        }
        else
        {
            //Other Field Is Invalid, do not validate current one
            return ValidationResult.Success;
        }
    }
}

【讨论】:

  • @archil : 你能给出一些伪代码吗?我无法完全关注你。
  • 你看过我提到的布拉德威尔逊的视频了吗?
  • 是的,我做了,那个视频是基于 mvc 3,我正在做的项目需要使用 mvc 2
  • 好的,然后你可以读Phil Haack's post about custom valitaion
  • Phil 的帖子很好,但我仍然无法弄清楚如何在 mvc 2 中做到这一点,有人可以帮助我。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-04
  • 1970-01-01
  • 2014-11-03
  • 1970-01-01
  • 1970-01-01
  • 2013-11-12
  • 1970-01-01
相关资源
最近更新 更多