繁体   English   中英

C# 验证嵌套 class 的自定义数据类型(枚举)的属性内的属性

[英]C# Validate attribute inside property of custom data type (enum) of a nested class

我需要以下帮助。 我有一个基础 class,比如 MyClass,它有一个嵌套的 class,比如 StandardOne。 在 StandardOne 中,我有一些我希望用属性验证的属性。 这些属性适用于常见的数据类型,即字符串、字符等,但我有一些基于简单枚举的属性。 此时,属性的验证不起作用,根据错误提示,因为强制转换。 我尝试了一切,但是,唉,没有成功。

  1. 谁能帮我解决错误?
  2. 我看到我在验证属性时一次又一次地做同样的代码; 关于如何(也许?)将其转换为扩展的任何建议? 我不知道.. 欢迎任何建议。

例子:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
                    
public class Program
{
    public static void Main()
    {
        Console.WriteLine("Start");
    }

    public class MyClass
    {
        public Standard_One Standard {get;set;}

        private string  _Name;

        public MyClass(string system_name)
        {
            this._Name = system_name;
            this.Standard = new Standard_One();
        }

        public class Standard_One
        {
            private string _MyProperty1;

            [Required(AllowEmptyStrings = false, ErrorMessage = "Field is mandatory.")]
            [StringLength(32, ErrorMessage = "Field value should be between Minimum 1 and Maximum 32 characters.", MinimumLength = 1)]
            [RegularExpression(@"^[a-zA-Z0-9.-]$", ErrorMessage = "Non-valid characters included.")]
            public string MyProperty1
            {
                get
                { return _MyProperty1; }
                set
                {
                    var context = new ValidationContext(value, null, null);
                    var results = new List<ValidationResult>();
                    var attributes = typeof(Standard_One)
                        .GetProperty("MyProperty1")
                        .GetCustomAttributes(true)
                        .OfType<ValidationAttribute>()
                        .ToArray();
                    
                    // All ok
                    if (!Validator.TryValidateValue(value, context, results, attributes))       
                    {
                        foreach (var result in results)
                        {Console.WriteLine("MyProperty1 error: {0}", result.ErrorMessage); }
                    }
                    else
                    {
                        Console.WriteLine("MyProperty1 set to {0}.", value);
                        _MyProperty1 = value;
                    }
                }
            }

            public enum field_sys_type { A, B, G }
            
            [Required(AllowEmptyStrings = false, ErrorMessage = "Field is mandatory.")]
            [StringLength(32, ErrorMessage = "Field value should be between Minimum 1 and Maximum 32 characters.", MinimumLength = 1)]
            [RegularExpression(@"^[a-zA-Z0-9.-]$", ErrorMessage = "Non-valid characters included.")]
            public field_sys_type MyProperty2
            {
                get
                { return _MyProperty2; }
                set
                {
                    var context = new ValidationContext(value, null, null);
                    var results = new List<ValidationResult>();
                    var attributes = typeof(Standard_One)
                        .GetProperty("MyProperty2")
                        .GetCustomAttributes(true)
                        .OfType<ValidationAttribute>()
                        .ToArray();
                    
                    // THROWS System.InvalidCastException: 'Unable to cast object of type 'field_sys_type' to type 'System.String'.'
                    if (!Validator.TryValidateValue(value, context, results, attributes))       
                    {
                        foreach (var result in results)
                        {Console.WriteLine("MyProperty2 error: {0}", result.ErrorMessage); }
                    }
                    else
                    {
                        Console.WriteLine("MyProperty2 set to {0}.", value);
                        _MyProperty2 = value;
                    }
                }
            }
            
        }
    }   // end of MyClass
}

您不应该在属性设置器内部进行验证。 你需要验证你的整个 object 看看例子: https://www.geekinsta.com/manually-validate-with-data-annotations/

 this._Name = system_name;
 this.Standard = new Standard_One();

 var ctx = new ValidationContext(this.Standard);

 // A list to hold the validation result.
 var results = new List < ValidationResult > ();

 if (!Validator.TryValidateObject(this.Standard, ctx, results, true)) {
   foreach(var errors in results) {
     Console.WriteLine("Error {0}", errors);
     return;
   }
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM