我有一个对象(标题),它有一个子对象(详细信息)列表,我希望在接受数据之前进行自定义验证。我已经尝试过ModelState.IsValid和TryValidateModel,但它似乎没有触发子对象上的Validate方法(只有头对象)。
因此,在提交时,我看到标题的验证火,但不是子对象。然后,如果我执行TryValidateModel,我再次看到(断点)验证方法在标题上调用,但不在子对象上调用。
带注释的验证(必须是数字等)似乎在处理子对象,而不是通过IValidatableObject接口添加的自定义逻辑。任何帮助将不胜感激。
答案 0 :(得分:1)
我创建了一个属性([ValidateObject]),它将验证你在课堂上放置的属性,就像你认为的那样。
public class Personne
{
[ValidateObject]
public Address Address { get; set; }
//[...]
}
(地址是一个自定义类。)
它可用于验证:
子对象的集合。
[ValidateObject]
public List<Address> Address { get; set; }
它支持多层次的部门,如果&#34;地址&#34;有一种类型&#34; ZipCode&#34;使用属性[ValidateObject],它将验证tho。
代码:
public class ValidateObjectAttribute : ValidationAttribute
{
public ValidateObjectAttribute()
{
}
private ValidationContext ValidationContext { get; set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
this.ValidationContext = validationContext;
var results = new List<ValidationResult>();
try
{
var isIterable = this.IsIterable(value);
if (isIterable)
{
int currentItemPosition = -1;
foreach (var objectToValidate in value as IEnumerable<object>)
{
currentItemPosition++;
var resultTemp = ValidationsForObject(objectToValidate, true, currentItemPosition);
if (resultTemp != null)
results.AddRange(resultTemp);
}
if (results.Count <= 0)
results = null;
}
else
results = ValidationsForObject(value);
if (results != null)
{
//Build a validation result
List<string> memberNames = new List<string>();
results.ForEach(r => memberNames.AddRange(r.MemberNames));
var compositeResultsReturn = new CompositeValidationResult($"Validation for {validationContext.DisplayName} failed!", memberNames.AsEnumerable());
results.ForEach(r => compositeResultsReturn.AddResult(r));
return compositeResultsReturn;
}
}
catch (Exception) { }
return ValidationResult.Success;
}
private List<ValidationResult> ValidationsForObject (object objectToValidate, bool IsIterable = false, int position = -1)
{
var results = new List<ValidationResult>();
var contextTemp = new ValidationContext(objectToValidate, null, null);
var resultsForThisItem = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(objectToValidate, contextTemp, resultsForThisItem, true);
if (isValid)
return null;
foreach (var validationResult in resultsForThisItem)
{
List<string> propNames = new List<string>();// add prefix to properties
foreach (var nameOfProp in validationResult.MemberNames)
{
if (IsIterable)
propNames.Add($"{this.ValidationContext.MemberName}[{position}].{nameOfProp}");
else
propNames.Add($"{this.ValidationContext.MemberName}.{nameOfProp}");
}
var customFormatValidation = new ValidationResult(validationResult.ErrorMessage, propNames);
results.Add(customFormatValidation);
}
return results;
}
private bool IsIterable(object value)
{
////COULD WRITE THIS, but its complicated to debug...
//if (value.GetType().GetInterfaces().Any(
//i => i.IsGenericType &&
//i.GetGenericTypeDefinition() == typeof(IEnumerable<>)))
//{
// // foreach...
//}
Type valueType = value.GetType();
var interfaces = valueType.GetInterfaces();
bool isIterable = false;
foreach (var i in interfaces)
{
var isGeneric = i.IsGenericType;
bool isEnumerable = i.GetGenericTypeDefinition() == typeof(IEnumerable<>);
isIterable = isGeneric && isEnumerable;
if (isIterable)
break;
}
return isIterable;
}
}
public class CompositeValidationResult : ValidationResult
{
private readonly List<ValidationResult> _results = new List<ValidationResult>();
public IEnumerable<ValidationResult> Results
{
get
{
return _results;
}
}
public CompositeValidationResult(string errorMessage) : base(errorMessage)
{
}
public CompositeValidationResult(string errorMessage, IEnumerable<string> memberNames) : base(errorMessage, memberNames)
{
}
protected CompositeValidationResult(ValidationResult validationResult) : base(validationResult)
{
}
public void AddResult(ValidationResult validationResult)
{
_results.Add(validationResult);
}
}
如果你的模型被正确绑定,这将有效:)
您可能希望添加必需属性,确保该对象本身不为null。
[Required]
希望有所帮助!
答案 1 :(得分:0)
我想知道你的root对象是否有阻止子验证的错误。 见Recursive validation using annotations and IValidatableObject 此URL提及该场景以及强制从根
对子项进行验证的代码根据从根对象
触发验证的帖子
public IEnumerable Validate(ValidationContext validationContext)
{
var context = new ValidationContext(this.Details, validationContext.ServiceContainer, validationContext.Items);
var results = new List();
Validator.TryValidateObject(this.Details, context, results);
return results;
}
答案 2 :(得分:0)
TryValidateObject似乎没有触发自定义验证,只触发数据注释?我通过执行以下操作,将详细信息验证添加到标头验证中:
foreach (var detail in this.Details)
{
var validationResults = detail.Validate(validationContext);
foreach (var validationResult in validationResults)
{
yield return validationResult;
}
}
这在验证方面起作用,但UI没有显示错误消息。即使我在UI上有ValidationMessagesFor。