问题: 我正在尝试手动验证某些 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/