Asp.net mvc 自定义验证属性ASP.NET MVC

Asp.net mvc 自定义验证属性ASP.NET MVC,asp.net-mvc,Asp.net Mvc,在ASP.NET MVC中,只有当不同的CustomValidationAttribute验证不同的字段时,才能在一个字段上执行CustomValidationAttribute 我的视图需要包含单独的日期和时间字段。我对这两种方法都有单独的自定义验证属性。但是,是否可能只有在日期验证属性验证为true时才检查时间验证属性 谢谢 时间验证属性已选中 仅当日期验证属性 验证为真 此语句表示自定义验证。是的,你能做到。您可以定义以其他字段的名称作为参数的自定义验证属性。然后,在重写的Validate

在ASP.NET MVC中,只有当不同的CustomValidationAttribute验证不同的字段时,才能在一个字段上执行CustomValidationAttribute

我的视图需要包含单独的日期和时间字段。我对这两种方法都有单独的自定义验证属性。但是,是否可能只有在日期验证属性验证为true时才检查时间验证属性

谢谢

时间验证属性已选中 仅当日期验证属性 验证为真

此语句表示自定义验证。是的,你能做到。您可以定义以其他字段的名称作为参数的自定义验证属性。然后,在重写的Validate()方法中,您可以通过名称获取另一个字段的PropertyInfo,然后获取验证属性并验证它们。得到结果后,您可以决定是否对第一个字段进行验证。在mvcConf上发表了关于验证的精彩文章

顺便说一下,您还可以实现IClientValidable来结束客户端验证

这是非常非常简单的代码,它需要一些参数检查和错误处理等,但我认为想法是明确的

 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:您能提供一些伪代码吗?我不能完全理解你。你看过我提到的Brad Wilson的视频了吗?是的,我看过了,那视频是基于mvc 3的,我正在做的项目需要使用mvc 2ok,你可以读到Phil的帖子很好,但我仍然不知道如何在mvc 2中做到这一点,有人能帮我吗。