2011-03-30 139 views
0

是否有可能在ASP.NET MVC中的一个字段上的CustomValidationAttribute只有在不同的CustomValidationAttribute验证不同字段时才能执行。自定义验证属性ASP.NET MVC

我的看法需要包含单独的日期和时间字段。我有两个单独的自定义验证属性。但是,是否有可能仅在日期验证属性验证为true时才检查时间验证属性?

谢谢。

+0

为什么你想这样做?如果日期和时间都无效,为什么不这样说呢?或者为什么不使用客户端验证来做到这一点,这将做你想要的? – arame3333 2011-03-30 07:11:15

回答

3

时验证属性检查 只有当日期验证属性 验证为真?

此声明表示自定义验证。是的,你可以做到这一点。您可以定义将其他字段的名称作为参数的自定义验证属性。然后,在重写的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; 
     } 
    } 
} 
+0

@archil:你能给一些伪代码吗?我无法完全跟随你。 – Jake 2011-03-30 07:17:43

+0

你检查了我提到的布莱德威尔逊的视频吗? – archil 2011-03-30 07:19:57

+0

是的,我做了,该视频是基于mvc 3,我正在开发的项目需要使用mvc 2 – Jake 2011-03-30 07:25:57