基于本文:带有数据注释的手动验证
我写这段代码:
public class Person04 { [CustomValidation(typeof(AWValidation), "ValidateSalesAmount")] public int SalesAmout { get; set; } [DataType(DataType.EmailAddress, ErrorMessage = "Invalid E-mail")] public string EmailAddress { get; set; } [Range(0, 99, ErrorMessage = "Age should be in range 0 to 99")] public int Age { get; set; } [Required(ErrorMessage="Name is required")] public string Name { get; set; } [StringLength(10, ErrorMessage = "Invalid Last Name")] public string LastName { get; set; } } public class AWValidation { public static ValidationResult ValidateSalesAmount(int salesAmount) { if (salesAmount < 0) { return new ValidationResult("Invalid Sales Amount"); } return ValidationResult.Success; } }
和
var person = new Person04() { SalesAmout = -1, Age = 100, EmailAddress = "nima", LastName = "Arian The Great" }; var context = new ValidationContext(person, serviceProvider: null, items: null); var results = new List(); var isValid = Validator.TryValidateObject(person, context, results); if (!isValid) { foreach (var validationResult in results) { Console.WriteLine(validationResult.ErrorMessage); } }
但是这段代码只写了1个错误:
名称为必填项
为什么未指定其他错误?
谢谢
var isValid = Validator.TryValidateObject(person, context, results, true);
您缺少最后一个布尔参数,该参数指示您要验证所有属性:
validateAllProperties:验证所有属性为true;否则为 false。如果为false,则仅验证必需的属性。