Custom ValidationAttribute test against whole model

孤者浪人 提交于 2019-11-30 09:55:48

问题


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 the other property and make a decision?

So;

public class QuickQuote
{
    public String state { get; set; }

    [MyRequiredValidator(ErrorMessage = "Error msg")]
    public String familyType { get; set; }

So in the above example, can the validator test to see what's in the "state" property and take that into consideration when validating "familyType"?

I know I can probably save the object to the session but would like to avoid any saving of state if possible.


回答1:


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"




回答2:


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.




回答3:


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
        }      
    }


来源:https://stackoverflow.com/questions/2649581/custom-validationattribute-test-against-whole-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!