递归使用验证注释和IValidatableObject [英] Recursive validation using annotations and IValidatableObject
问题描述
我想验证嵌套的对象(在MVC senss不机型),使用说明和一些自定义的code。
I am trying to validate nested objects (not models in the MVC senss) using annotations and some custom code.
我发现下面的职位有用
<一个href=\"http://stackoverflow.com/questions/6938877/using-data-annotations-validation-manually-and-object-graphs\">Using数据注释验证手动和对象图
作为一个答案的建议,我已经创建了一个额外的程序在容器类验证嵌套对象。这里是我修改的测试code
As suggested in an answer, I've created an extra routine in the container class to validate the nested object. Here's my modified test code
public class Customer : IValidatableObject
{
public Customer()
{
Details = new CustomerDetails();
}
[Required]
[MaxLength(2)]
public string Name
{
get;
set;
}
public CustomerDetails Details
{
get;
private set;
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var context = new ValidationContext(this.Details, validationContext.ServiceContainer, validationContext.Items);
var results = new List<ValidationResult>();
Validator.TryValidateObject(this.Details, context, results);
return results;
}
}
不过,我有一个获得的所有的验证错误,设置为true validateAllProperties调用TryValidateObject即使问题。
However I have problems getting all the validation errors, even when calling TryValidateObject with validateAllProperties set to true.
var context = new ValidationContext(cs, null, null);
var results = new List<ValidationResult>();
Validator.TryValidateObject(cs, context, results,true);
如果有在容器中的任何错误,只有这些显示。只有当有容器对象中没有错误,在嵌套对象错误显示。我怀疑这事做与验证rouine返回一个完整列表,并且不能够从容器添加到(现有的)列表(?)
If there are any errors in the container, only these will show. Only when there are no errors in the container object, errors in the nested object will show. I suspect it has something to do with the Validate rouine returning a full list, and not being able to add to an (existing) list from the container(?)
是否有任何修改,我可以作出例行程序来获取所有的错误显示?
Are there any modifications I can make to routine to get all errors to show?
推荐答案
看到这个答案: http://stackoverflow.com/a /七十二万四千九百四十四分之三百四十零万零六百二十七
因此,有在你的类'atributes一个错误,因此验证方法不会被调用。
我建议使用<一个href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.customvalidationattribute.aspx\"相对=nofollow> CustomValidationAttribute 是这样的:
So, there is an error in your class' atributes, and therefore Validate method doesn't get called. I suggest using CustomValidationAttribute like this:
[CustomValidation(typeof(Customer), "ValidateRelatedObject")]
public CustomerDetails Details
{
get;
private set;
}
public static ValidationResult ValidateRelatedObject(object value, ValidationContext context)
{
var context = new ValidationContext(value, validationContext.ServiceContainer, validationContext.Items);
var results = new List<ValidationResult>();
Validator.TryValidateObject(value, context, results);
// TODO: Wrap or parse multiple ValidationResult's into one ValidationResult
return result;
}
这篇关于递归使用验证注释和IValidatableObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!