GWB*_*GWB 38 c# validation data-annotations
验证父对象时是否可以自动验证复杂的子对象,并将结果包含在已填充的对象中ICollection<ValidationResult>?
如果我运行以下代码:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace ConsoleApplication1
{
public class Person
{
[Required]
public string Name { get; set; }
public Address Address { get; set; }
}
public class Address
{
[Required]
public string Street { get; set; }
[Required]
public string City { get; set; }
[Required]
public string State { get; set; }
}
class Program
{
static void Main(string[] args)
{
Person person = new Person
{
Name = null,
Address = new Address
{
Street = "123 Any St",
City = "New York",
State = null
}
};
var validationContext = new ValidationContext(person, null, null);
var validationResults = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(person, validationContext, validationResults);
Console.WriteLine(isValid);
validationResults.ForEach(r => Console.WriteLine(r.ErrorMessage));
Console.ReadKey(true);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我得到以下输出:
False
The Name field is required.
但我期待类似的东西:
False
The Name field is required.
The State field is required.
我提供了一个更好的子对象验证解决方案的赏金,但没有得到任何接受者,理想情况下
我仍然感到惊讶,框架不支持这一点.
Kyl*_*Mit 28
这是不幸的是,标准的行为Validator.TryValidateObject,其
不会递归验证对象的属性值
正如Jeff Handley关于使用Validator验证对象和属性的文章所指出的,默认情况下,验证器将按顺序验证:
IValidatableObject问题是,在每一步......
如果任何验证器无效,
Validator.ValidateObject将中止验证并返回故障
另一个可能的问题是模型绑定器只对它决定绑定的对象运行验证.例如,如果不为模型上的复杂类型中的字段提供输入,则模型绑定器根本不需要检查这些属性,因为它没有在这些对象上调用构造函数.根据Brad Wilson关于ASP.NET MVC中输入验证与模型验证的精彩文章:
我们没有递归地"潜入"Address对象的原因是表单中没有任何内容绑定Address中的任何值.
解决此问题的一种方法是通过向属性添加自定义验证属性,将对象级验证转换为属性级验证,该属性将返回对象本身的验证结果.
Josh Carroll关于使用DataAnnotations的递归验证的文章提供了一种这样的策略的实现(最初在这个SO问题中).如果我们想要验证复杂类型(如Address),我们可以向ValidateObject属性添加自定义属性,因此在第一步中对其进行评估
public class Person {
[Required]
public String Name { get; set; }
[Required, ValidateObject]
public Address Address { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
您需要添加以下ValidateObjectAttribute实现:
public class ValidateObjectAttribute: ValidationAttribute {
protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
var results = new List<ValidationResult>();
var context = new ValidationContext(value, null, null);
Validator.TryValidateObject(value, context, results, true);
if (results.Count != 0) {
var compositeResults = new CompositeValidationResult(String.Format("Validation for {0} failed!", validationContext.DisplayName));
results.ForEach(compositeResults.AddResult);
return compositeResults;
}
return ValidationResult.Success;
}
}
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);
}
}
Run Code Online (Sandbox Code Playgroud)
对于实现的对象IValidatableObject,当我们检查ModelState时,我们还可以在返回错误列表之前检查模型本身是否有效.我们可以通过调用添加我们想要的任何错误.如" 如何强制MVC验证IValidatableObject"中所述,我们可以这样做:ModelState.AddModelError(field, error)
[HttpPost]
public ActionResult Create(Model model) {
if (!ModelState.IsValid) {
var errors = model.Validate(new ValidationContext(model, null, null));
foreach (var error in errors)
foreach (var memberName in error.MemberNames)
ModelState.AddModelError(memberName, error.ErrorMessage);
return View(post);
}
}
Run Code Online (Sandbox Code Playgroud)
此外,如果您想要一个更优雅的解决方案,您可以通过在Application_Start()中提供自己的自定义模型绑定器实现来编写代码一次
ModelBinderProviders.BinderProviders.Add(new CustomModelBinderProvider());.这里和这里有很好的实现
Aar*_*els 10
我也碰到了这个,发现了这个帖子.这是第一关:
namespace Foo
{
using System.ComponentModel.DataAnnotations;
using System.Linq;
/// <summary>
/// Attribute class used to validate child properties.
/// </summary>
/// <remarks>
/// See: http://stackoverflow.com/questions/2493800/how-can-i-tell-the-data-annotations-validator-to-also-validate-complex-child-pro
/// Apparently the Data Annotations validator does not validate complex child properties.
/// To do so, slap this attribute on a your property (probably a nested view model)
/// whose type has validation attributes on its properties.
/// This will validate until a nested <see cref="System.ComponentModel.DataAnnotations.ValidationAttribute" />
/// fails. The failed validation result will be returned. In other words, it will fail one at a time.
/// </remarks>
public class HasNestedValidationAttribute : ValidationAttribute
{
/// <summary>
/// Validates the specified value with respect to the current validation attribute.
/// </summary>
/// <param name="value">The value to validate.</param>
/// <param name="validationContext">The context information about the validation operation.</param>
/// <returns>
/// An instance of the <see cref="T:System.ComponentModel.DataAnnotations.ValidationResult"/> class.
/// </returns>
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var isValid = true;
var result = ValidationResult.Success;
var nestedValidationProperties = value.GetType().GetProperties()
.Where(p => IsDefined(p, typeof(ValidationAttribute)))
.OrderBy(p => p.Name);//Not the best order, but at least known and repeatable.
foreach (var property in nestedValidationProperties)
{
var validators = GetCustomAttributes(property, typeof(ValidationAttribute)) as ValidationAttribute[];
if (validators == null || validators.Length == 0) continue;
foreach (var validator in validators)
{
var propertyValue = property.GetValue(value, null);
result = validator.GetValidationResult(propertyValue, new ValidationContext(value, null, null));
if (result == ValidationResult.Success) continue;
isValid = false;
break;
}
if (!isValid)
{
break;
}
}
return result;
}
}
}
Run Code Online (Sandbox Code Playgroud)
您需要创建自己的验证器属性(例如[CompositeField]),以验证子属性.