xVal, DataAnnotations on the entire class

百般思念 提交于 2020-01-03 17:25:39

问题


I have a complete validation on an obeject and am trying to figure out the best way to handle it.

Given the following class:

public class LetterResponse {
 public Guid Id {get;set;}
 public bool SendBlankCart {get;set;}
 public string ToName {get;set;}
 public string ToAddress {get;set;}
}

I want to use a dataannotation and xval in order to validate the class before I persist it, but I have complex validation that requires more than one property.

Pseudo:

if SendBlankCart {
 - no validation on ToName, ToAddress 
} else {
 ToName - required.
 ToAddress - required. 
}

I would like to annotate like this:

[LetterResponseValidator]
public class LetterResponse {
 public Guid Id {get;set;}
 public bool SendBlankCart {get;set;}
 public string ToName {get;set;}
 public string ToAddress {get;set;}
}

and have a validation rule like this:

public class LetterResponseValidator : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            if (value.GetType() == typeof(LetterResponse))
            {
                var letterResponse = (letterResponse) value;
                if (letterResponse.SendBlankCard)
                {
                    return true;
                } else
                {
                    if (string.IsNullOrEmpty(letterResponse.FromDisplayName) || string.IsNullOrEmpty(letterResponse.ToAddress1))
                    {
                        return false;
                    }
                    return true;
                }

            }
            return false;
        }
    }

I am expecting the parameter to be my instance of the LetterResponse class, but it never gets called on my validation runner?

Does anyone know a way to handle this?

Thanks,

Hal


回答1:


I don't think this has to do with the fact that you have a class-level validator. To exclude any connection, try applying a dummy required validator to "ToName" and see if the validator is called or not.

If it is being called, then let me know, if it's not, then you should check if you have overriden your standard modelbinder with the DataAnnotationsModelBinder in your Global.asax.cs file:

ModelBinders.Binders.DefaultBinder = new DataAnnotationsModelBinder();

For more details on this and fully working demo project, read this blog article about client-side validation.



来源:https://stackoverflow.com/questions/1348218/xval-dataannotations-on-the-entire-class

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