开发者

Custom Validation Attribute ASP.NET MVC

Is it possible in ASP.NET MVC for a CustomValidationAttribute on one field to execute only if a different CustomValidationAttribute validates a different field.

My view needs to contain separate date and time fields. I have separate custom validation attributes for both. But is it possible that the time validation attribute is checked only when date validation attribute valid开发者_开发知识库ates to true ?

Thanks.


time validation attribute is checked only when date validation attribute validates to true ?

This statement means custom validation. Yes, you can do this. You Could Define custom validation attribute that takes other field's name as parameter. Then, in overrided Validate() method, you could get PropertyInfo for that other field by the name, then get validation attributes and validate them. After getting the result, you could decide whether to do validation on first field or not. Brad Wilson had great post on mvcConf about validation

By the way, you could also implement IClientValidatable to wrap up client side validation

This is the very very sample code and it needs some argument checking and error handling, etc. But i think idea is clear

 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜