xVal,整个类的DataAnnotations

问题描述 投票:4回答:1

我对一个对象进行了完整的验证,并试图找出处理它的最佳方法。

鉴于以下课程:

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

我想使用dataannotation和xval来在我持久化之前验证类,但是我需要复杂的验证,需要多个属性。

伪:

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

我想这样注释:

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

并有一个像这样的验证规则:

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

我期待参数是我的LetterResponse类的实例,但它永远不会在我的验证运行器上调用?

有谁知道处理这个的方法?

谢谢,

案件

c# asp.net-mvc data-annotations xval
1个回答
3
投票

我不认为这与你有一个类级验证器的事实有关。要排除任何连接,请尝试将虚拟必需验证器应用于“ToName”,并查看是否调用验证器。

如果它被调用,那么让我知道,如果不是,那么你应该检查你是否已使用Global.asax.cs文件中的DataAnnotationsModelBinder覆盖标准模型绑定器:

ModelBinders.Binders.DefaultBinder = new DataAnnotationsModelBinder();

有关此完整工作演示项目的更多详细信息,请阅读此blog article about client-side validation

© www.soinside.com 2019 - 2024. All rights reserved.