Custom validation that checks if email already exists in DB. HELP!
I'm new to .net MVC but am making heads way. I'm trying to make a custom DataAnnotation validator that checks to see if an email address is already registered. I am using LINQ to SQL. My Model is below:
// 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;
}
}
Controller code:
[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 RedirectTo开发者_StackOverflowAction("confirm", "login");
}
return View(user);
}
All the other validations work but the ExistingEmailCheck doesn't. No error, nothing. Any Ideas?? Help is much appreciated.
Shahid
Shouldn't you apply the filter to the specific Property instead of the Class?
精彩评论