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

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

问题描述

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

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

我得到以下输出:




名称字段是必填字段。

但是我期望类似于以下内容:

But I was expecting something similar to:




名称字段为必填项。

必须填写州字段。






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


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天全站免登陆