【问题标题】:Validator ignoring MaxLength attributes验证器忽略 MaxLength 属性
【发布时间】:2018-05-15 01:25:00
【问题描述】:

问题: 我正在尝试手动验证一些 c# 对象,而验证器忽略了与字符串长度相关的验证。

测试用例: 扩展使用 [Required] 属性的this example,我还想验证字符串是否太长,如下所示。

public class Recipe
{
    //[Required]
    public string Name { get; set; }

    [MaxLength(1)] public string difficulty = "a_string_that_is_too_long";
}

public static void Main(string[] args)
{

    var recipe = new Recipe();
    var context = new ValidationContext(recipe, serviceProvider: null, items: null);
    var results = new List<ValidationResult>();

    var isValid = Validator.TryValidateObject(recipe, context, results);

    if (!isValid)
    {
        foreach (var validationResult in results)
        {
            Console.WriteLine(validationResult.ErrorMessage);
        } 
    } else {
        Console.WriteLine("is valid");
    }
}

预期结果:错误:“难度太长。”

实际结果:'有效'

其他测试的东西:

【问题讨论】:

  • 您可以将= 更改为=&gt; 以将其切换为属性

标签: c#


【解决方案1】:

您需要进行 2 处更改才能使验证按您期望的方式工作:

1.您必须将difficulty 字段更改为属性。

Validator 类仅验证属性,因此将difficulty 定义更改为如下属性:

[MaxLength(1)] public string difficulty { get; set; } = "a_string_that_is_too_long";

2。为Validator.TryValidateObject 调用指定validateAllProperties: true 参数。

Validator.TryValidateObjectdocumentation 并不是很明确,除非您使用带有 validateAllProperties: true 的重载,否则只会检查 Required 属性。所以修改调用如下:

var isValid = Validator.TryValidateObject(recipe,
                                          context,
                                          results,
                                          validateAllProperties: true);

【讨论】:

  • 好吧,我想这意味着即使他们在msdn.microsoft.com/en-us/library/… 的示例代码也不起作用......(这只是一个具有属性的字段)
  • 唯一的问题是 TryValidateObject 现在将通过异常处理其他违规行为。似乎并没有很努力地“尝试”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-11
  • 2018-03-21
  • 2014-04-04
  • 1970-01-01
  • 2021-12-23
相关资源
最近更新 更多