检查电子邮件是否已存在于数据库中的自定义验证。帮助!
我是 .net MVC 的新手,但正在取得进展。我正在尝试制作一个自定义 DataAnnotation 验证器来检查电子邮件地址是否已注册。我正在使用 LINQ to SQL。我的模型如下:
// Model
public class UsersRepository
{
private DigitalentDataContext db = new DigitalentDataContext();
BaseController baseController = new BaseController();
//
// Add talent user
public void AddTalentUser(User user, TalentDetail talentDetail)
{
user.TalentDetails.Add(talentDetail);
db.Users.InsertOnSubmit(user);
db.SubmitChanges();
string activationID = user.ActivationID.ToString();
string activationEmail = user.Email;
baseController.SendConfEmail(activationID, activationEmail);
}
public IQueryable<User> GetAllUsers()
{
return db.Users;
}
}
//Validation
[MetadataType(typeof(UserValidation))]
public partial class User { }
[Bind(Exclude = "UserID")]
[ExistingEmailCheck("Email", ErrorMessage="Email address already registered")]
public class UserValidation
{
[Required(ErrorMessage = "First name required"), StringLength(20, MinimumLength=3, ErrorMessage = "Must be between 3 and 20 characters")]
public string FirstName { get; set; }
...
}
public class ExistingEmailCheckAttribute : ValidationAttribute
{
public ExistingEmailCheckAttribute(string emailToCheck) {
EmailToCheck = emailToCheck;
}
public string EmailToCheck { get; private set; }
private UsersRepository _UserRep = new UsersRepository();
public override bool IsValid(object value)
{
int existingEmailCount = _UserRep.GetAllUsers().Where(g => g.Email == EmailToCheck).Count();
return existingEmailCount == 0;
}
}
控制器代码:
[HttpPost]
public ActionResult Signup(User user, TalentDetail talentDetail)
{
if (ModelState.IsValid) {
user.ActivationID = System.Guid.NewGuid();
user.ActivationStatus = false;
user.DateCreated = DateTime.Now;
userRepository.AddTalentUser(user, talentDetail);
return RedirectToAction("confirm", "login");
}
return View(user);
}
所有其他验证都有效,但 ExistingEmailCheck 无效。没有错误,什么都没有。有什么想法吗?非常感谢您的帮助。
沙希德
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
难道您不应该将过滤器应用于特定的属性而不是类吗?
Shouldn't you apply the filter to the specific Property instead of the Class?