C# 验证不需要';t fire(System.ComponentModel.DataAnnotations)
我这里有一个类,有两个属性C# 验证不需要';t fire(System.ComponentModel.DataAnnotations),c#,validation,attributes,system.componentmodel,C#,Validation,Attributes,System.componentmodel,我这里有一个类,有两个属性Name和Age using System.ComponentModel.DataAnnotations; public class Person { [Required(AllowEmptyStrings = false)] [StringLength(25, MinimumLength = 2)] [RegularExpression(@"^[a-zA-Z]+$")] public string Name { get; set; }
Name
和Age
using System.ComponentModel.DataAnnotations;
public class Person
{
[Required(AllowEmptyStrings = false)]
[StringLength(25, MinimumLength = 2)]
[RegularExpression(@"^[a-zA-Z]+$")]
public string Name { get; set; }
[Range(0, 100)]
public int Age { get; set; }
}
我尝试验证这些值
Person pTemp = new Person();
pTemp.Name = "x"; //invalid because length <2
pTemp.Age = 200; //invalid because > 100
//validation here
var context = new ValidationContext(pTemp);
var results = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(pTemp, context, results);
results.ForEach(x => Console.WriteLine(x.ErrorMessage));
Person pTemp=new Person();
pTemp.Name=“x”//无效,因为长度为100
//在此验证
var context=新的ValidationContext(pTemp);
var results=新列表();
var isValid=Validator.TryValidateObject(pTemp、上下文、结果);
results.ForEach(x=>Console.WriteLine(x.ErrorMessage));
但是唯一激发的验证属性是[必需]
我的错误在哪里?使用另一个重载:
var isValid=Validator.TryValidateObject(pTemp,context,results,true)代码>
从MSDN:
public static bool TryValidateObject(
Object instance,
ValidationContext validationContext,
ICollection<ValidationResult> validationResults,
bool validateAllProperties
)
公共静态bool TryValidateObject(
对象实例,
ValidationContext ValidationContext,
i收集验证结果,
布尔验证所有属性
)
验证所有属性
类型:System.Boolean
true以验证所有属性;如果为false,则仅验证必需的属性
由于默认情况下bool
等于false
,因此您只验证了必需的属性