DataAnnotations tryvalidateobject始终返回true [英] DataAnnotations tryvalidateobject always returns true

查看:119
本文介绍了DataAnnotations tryvalidateobject始终返回true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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);

                }

            }
        }


推荐答案

验证器将忽略字段中的 [RequiredAttribute] -它仅考虑一个属性;因此出于 Validator.Validate 的目的-将您的课程更改为:

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; }
}

这篇关于DataAnnotations tryvalidateobject始终返回true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆