Compare Email Address entered to database with DataAnnotations

吃可爱长大的小学妹 提交于 2019-12-12 08:56:14

问题


I have a class in my model in 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()
    {

    }
}

The Email address entered is stored in :

    public string Email { get; set; }

I need to compare that Email address to all the email addresses stored in the database using Data Annotation. I assume I will need a Custom Data Annotation? But I have no idea how to do it.

This is an example of the query to get al the email addresses from the database:

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

回答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 can help you to create custom validation. Then, to check user is already exist in database by email, try:

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



回答3:


In this post you'll find a solution leveraging FluentValidation, which implements a custom DataAnnotation.

Your Unique Email Validation would look something along these lines:

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


来源:https://stackoverflow.com/questions/21903355/compare-email-address-entered-to-database-with-dataannotations

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