【问题标题】:Compare Email Address entered to database with DataAnnotations将输入到数据库的电子邮件地址与 DataAnnotations 进行比较
【发布时间】:2014-02-20 09:22:33
【问题描述】:

我在 MVC 的模型中有一个类:

public class NewModel
{
    public bool AllComplexes { get; set; }
    public int UserID { get; set; }
    public int? RoleID { get; set; }
    public int ComplexID { get; set; }

    [Required(ErrorMessage = "Please enter a user name."), StringLength(50)]
    public string Username { get; set; }

    [Required(ErrorMessage = "Please enter Password"), StringLength(100, ErrorMessage = "Password cannot be longer than 100 characters")]
    public string Password { get; set; }

    [Compare("Password", ErrorMessage = "Passwords do not match")]
    [Required(ErrorMessage = "Please confirm Password")]
    public string RetypePassword { get; set; }

    [RegularExpression( "^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*@[a-z0-9-]+(\\.[a-z0-9]+)*\\.([a-z]{2,4})$" , ErrorMessage = "Invalid email format." )]
    [Required(ErrorMessage = "Please enter your e-mail address."), StringLength(50)]
    public string Email { get; set; }

    public List<NEWCategoryModel> Categories { get; set; }
    //public List<NEWPrivilegeModel> userPrivList { get; set; }
    public List<DropDownItem> ComplexList { get; set; }
    public List<DropDownItem> RoleList { get; set; }
    public string NewRole { get; set; }

    public NewModel()
    {

    }
}

输入的电子邮件地址存储在:

    public string Email { get; set; }

我需要使用数据注释将该电子邮件地址与存储在数据库中的所有电子邮件地址进行比较。我假设我需要自定义数据注释?但我不知道该怎么做。

这是从数据库中获取所有电子邮件地址的查询示例:

  db.ContactInformations.Where(x => x.EMail != null).Select(x => x.EMail);

【问题讨论】:

    标签: c# asp.net-mvc email data-annotations modelstate


    【解决方案1】:
    public class NewModel 
    {
          [EmailValidation(ErrorMessage = "The Email Address already exists")]
          [RegularExpression( "^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*@[a-z0-9-]+(\\.[a-z0-9]+)*\\.([a-z]{2,4})$" , ErrorMessage = "Invalid email format." )]
          [Required(ErrorMessage = "Please enter your e-mail address."), StringLength(50)]
          public string Email { get; set; }
    {
    
    
    public class EmailValidation : ValidationAttribute
    {
    
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            PropmetEntities db = new PropmetEntities();
            if (value != null)
            {
                var valueAsString = value.ToString();
                IEnumerable<string> email = db.ContactInformations.Where(x => x.EMail != null).Select(x => x.EMail);
                if (email.Contains(valueAsString))
                {
                    var errorMessage = FormatErrorMessage(validationContext.DisplayName);
                    return new ValidationResult(errorMessage);
                }
            }
            return ValidationResult.Success;
        }
    }
    

    【讨论】:

      【解决方案2】:

      This 可以帮助您创建自定义验证。然后,通过电子邮件检查用户是否已存在于数据库中,尝试:

      bool exist = db.UserTable.Any(e => e.Email.ToLower() == emailValue.ToLower());
      

      【讨论】:

      • 我编辑了我的答案,使用该链接,将存在逻辑添加到 IsValid 方法中。
      • 这个.ToLower() 创建新字符串并让垃圾收集器参与其中。
      【解决方案3】:

      this post 中,您将找到一个利用FluentValidation 的解决方案,它实现了自定义DataAnnotation。

      您的唯一电子邮件验证看起来应该是这样的:

      [Validator(typeof(NewModelValidator))]
      class NewModel
      {
          //...Model implementation omitted
      }
      
      public class NewModelValidator : AbstractValidator<NewModel>
      {
          public NewModelValidator()
          {
      
              RuleFor(x => x.Email).Must(IsUnieuqEmail).WithMessage("Email already exists");
          }
      
          private bool IsUniqueEmail(string mail)
          {
              var _db = new DataContext();
              if (_db.NewModel.SingleOrDefault(x => x.Email == mail) == null) return true;
              return false;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-08-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多