DataAnnotations tryvalidateobject always returns true

廉价感情. 提交于 2019-12-10 21:41:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!