问题
namespace ClassValidation
{
public class Student
{
[Required(ErrorMessage = "Name is required")]
public String Firstname;
[Required(ErrorMessage = "Email is required")]
public String personalEmail;
}
}
private static void Main(string[] args)
{
Student student = new Student();
student.personalEmail = "del";
ValidationContext context = new ValidationContext(student, null, null);
List<ValidationResult> results = new List<ValidationResult>();
bool valid = Validator.TryValidateObject(student, context, results, true);
if (!valid)
{
foreach (ValidationResult vr in results)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Write(" :: {0}{1}", vr.ErrorMessage, Environment.NewLine);
}
}
}
回答1:
The validator ignores the [RequiredAttribute]
on fields - it takes into an account only properties; so for purposes of Validator.Validate
- change your class to:
public class Student
{
[Required(ErrorMessage = "Name is required")]
public String Firstname { get; set; }
[Required(ErrorMessage = "Email is required")]
public String personalEmail { get; set; }
}
回答2:
If you dig into the validator source you will notice that TryValidateObject
will only validate properties, not fields. More specifically, you will notice it's use of GetObjectPropertyValidationErrors (which omits fields).
I see no real reason for you to be using public fields here anyway therefore the simplest fix is to use properties
public class Student
{
[Required(ErrorMessage = "Name is required")]
public string FirstName { get; set; }
[Required(ErrorMEssage = "Email is required")]
public string PersonalEmail { get; set; }
}
来源:https://stackoverflow.com/questions/29743595/dataannotations-tryvalidateobject-always-returns-true