当数据无效时,C# DataAnnotation 不会抛出异常?
C# DataAnnotation doesn't throw exception when data is invalid?
我使用数据得到了一个非常快速的代码定义:
using System.ComponentModel.DataAnnotations;
class UseDataAnnotations
{
[Required(ErrorMessage = "Name is compulsory")]
[StringLength(20)]
[RegularExpression(@"^[A-Z]{5, 20}$")]
public string Name { get; set; }
}
class Program
{
public static void Main(String [] args)
{
UseDataAnnotations obj = new UseDataAnnotations();
obj.Name = null;
var context = new ValidationContext(obj, null, null);
var result = new List<ValidationResult>();
bool IsValid = Validator.TryValidateObject(
obj,
context,
null,
true);
Console.WriteLine(IsValid);
foreach(var x in result)
{
Console.WriteLine(x.ErrorMessage);
}
}
}
我希望:只要 "Name" 字段为空,所有检查都应该失败并抛出某种异常。
但是在 运行 这个程序上,它只是打印 "False" 没有发生其他事情。那么我哪里错了,我的 "DataAnnotation" 是否有效?
我用的是vs2017。非常感谢。
验证工作正常,您可以按预期获得 false
,但是,您没有在 TryValidateObject
方法上传递 result
来填充错误。例如:
UseDataAnnotations obj = new UseDataAnnotations();
obj.Name = null;
var context = new ValidationContext(obj, null, null);
var result = new List<ValidationResult>();
// pass the result here as the argument to fill it up with the erros.
bool IsValid = Validator.TryValidateObject(obj, context, result, true);
Console.WriteLine(IsValid);
foreach(var x in result)
{
Console.WriteLine(x.ErrorMessage);
}
在此处查看工作示例:https://dotnetfiddle.net/lI3z1M
我使用数据得到了一个非常快速的代码定义:
using System.ComponentModel.DataAnnotations;
class UseDataAnnotations
{
[Required(ErrorMessage = "Name is compulsory")]
[StringLength(20)]
[RegularExpression(@"^[A-Z]{5, 20}$")]
public string Name { get; set; }
}
class Program
{
public static void Main(String [] args)
{
UseDataAnnotations obj = new UseDataAnnotations();
obj.Name = null;
var context = new ValidationContext(obj, null, null);
var result = new List<ValidationResult>();
bool IsValid = Validator.TryValidateObject(
obj,
context,
null,
true);
Console.WriteLine(IsValid);
foreach(var x in result)
{
Console.WriteLine(x.ErrorMessage);
}
}
}
我希望:只要 "Name" 字段为空,所有检查都应该失败并抛出某种异常。
但是在 运行 这个程序上,它只是打印 "False" 没有发生其他事情。那么我哪里错了,我的 "DataAnnotation" 是否有效?
我用的是vs2017。非常感谢。
验证工作正常,您可以按预期获得 false
,但是,您没有在 TryValidateObject
方法上传递 result
来填充错误。例如:
UseDataAnnotations obj = new UseDataAnnotations();
obj.Name = null;
var context = new ValidationContext(obj, null, null);
var result = new List<ValidationResult>();
// pass the result here as the argument to fill it up with the erros.
bool IsValid = Validator.TryValidateObject(obj, context, result, true);
Console.WriteLine(IsValid);
foreach(var x in result)
{
Console.WriteLine(x.ErrorMessage);
}
在此处查看工作示例:https://dotnetfiddle.net/lI3z1M