c# – 将输入数据库的电子邮件地址与DataAnnotations进行比较
发布时间:2020-12-16 02:00:11 所属栏目:百科 来源:网络整理
导读:我在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.
我在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; } 我需要使用Data Annotation将该电子邮件地址与存储在数据库中的所有电子邮件地址进行比较.我想我需要一个自定义数据注释?但我不知道该怎么做. 这是从数据库获取电子邮件地址的查询示例: db.ContactInformations.Where(x => x.EMail != null).Select(x => x.EMail); 解决方法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,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; } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |