c# - 验证器忽略 MaxLength 属性

标签 c#

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

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

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

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

实际结果:'有效'

其他测试内容:

  • 验证器正在运行,取消对 [Required] 的注释会导致消息“The Name field is required.”。
  • 改为使用 [StringLength](如前所述 在https://stackoverflow.com/a/6802739/432976 ) 没有区别。

最佳答案

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

<强>1。您必须将 difficulty 字段更改为属性。

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

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

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

documentation对于 Validator.TryValidateObject 不是很清楚这样一个事实,除非您将重载与 validateAllProperties: true 一起使用,否则只有 Required 属性将是检查。所以像这样修改调用:

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

关于c# - 验证器忽略 MaxLength 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47584920/

相关文章:

c# - 如何从数码相机中获取录制的视频?

c# - 如何有条件地对两个列表的字段求和

c# - 适用于 UWP 的 Google OAuth v2

c# - 我们如何在 C# 中解释 => Something => Something2 => Something3

c# - Process.Start() 在后台线程上运行时挂起

c# - 在 C# 中链接方法时如何进行转换

c# - 如何按二次方数量按网格部分分组?

c# - 如何创建文本文件并将其保存到共享目录?

c# - 从 XSD 生成 SQL Server 数据库

c# - 使用 LINQ 和 lambda 将字符串置于正确的大小写形式