Custom ValidationAttribute test against whole model

前端 未结 3 1272
执笔经年
执笔经年 2020-12-22 11:12

I know this is probably not possible but let\'s say I have a model with two properties.

I write a ValidationAttribute for one of the properties. Can that VA look at

相关标签:
3条回答
  • 2020-12-22 11:33

    Another way to achieve this kind of validation is to have your model implement IDataErrorInfo. That way you can do whole viewmodel validation.

    This page has some information about iplementing the IDataErrorInfo Interface, about 2/3 of the way down under the heading "mplementing the IDataErrorInfo Interface"

    0 讨论(0)
  • 2020-12-22 11:33

    Use ValidationContext to get your model:

     public class MyRequiredValidator: RequiredAttribute
        {
            public override bool RequiresValidationContext
            {
                get {return true;} //it needs another propertie in model            
            }
    
            protected override ValidationResult IsValid(object value, ValidationContext validationContext)
            {
                QuickQuote model = (QuickQuote)validationContext.ObjectInstance;
    
                if (model.state == "single")
                    return null;
                else
                    return base.IsValid(value, validationContext);//familyType is require for married
            }      
        }
    
    0 讨论(0)
  • 2020-12-22 11:34

    Your custom validation could be applied to the class directly, take a look at PropertiesMustMatch attribute in the AccountModels class that is created by default as a part of the MVC project template in VS2008.

    0 讨论(0)
提交回复
热议问题