如何告诉数据注释验证器也验证复杂的子属性? [英] How can I tell the Data Annotations validator to also validate complex child properties?

查看:25
本文介绍了如何告诉数据注释验证器也验证复杂的子属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在验证父对象时自动验证复杂的子对象并将结果包含在填充的 ICollection 中?

Can I automatically validate complex child objects when validating a parent object and include the results in the populated 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);
        }
    }
}

我得到以下输出:

错误
名称字段是必需的.

但我期待类似的东西:

错误
名称字段是必需的.
State 字段是必需的.

<小时>

我提供了一个更好的子对象验证解决方案的赏金,但没有得到任何接受者,理想情况下


I offered a bounty for a better child object validation solution but didn't get any takers, ideally

  • 验证子对象到任意深度
  • 处理每个对象的多个错误
  • 正确识别子对象字段上的验证错误.

我仍然对框架不支持这一点感到惊讶.

I'm still surprised the framework doesn't support this.

推荐答案

您需要创建自己的验证器属性(例如,[CompositeField])来验证子属性.

You will need to make your own validator attribute (eg, [CompositeField]) that validates the child properties.

这篇关于如何告诉数据注释验证器也验证复杂的子属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆