I have a registration page and you want to do some verification (in addition to StringLength and Required annotations on my ViewModel) to duplicate usernames and email addresses. I am currently doing this check in my controller when the registration form is sent back. I am not sure if this is the right place for this.
I cannot imagine that the ViewModel is the right place, since the ViewModel will need a link to my UserRepository. Does it make sense to have such validation in model classes?
If so, how to implement this on a model to check if the information is valid before I sent it to my repository?
Update
My controller action code:
if (ModelState.IsValid)
{
if (!_userRepository.Exists(registerViewModel.Username))
{
if (!_userRepository.EmailExists(registerViewModel.Email))
{
_userRepository.Add(
new User
{
Created = DateTime.Now,
Email = registerViewModel.Email,
Password = registerViewModel.Password,
Username = registerViewModel.Username
});
_userRepository.SaveChanges();
TempData["registrationDetails"] = registerViewModel;
return RedirectToAction("Confirm");
}
else
{
ModelState.AddModelError(string.Empty, "This email address is already in use.");
}
}
else
{
ModelState.AddModelError(string.Empty, "This username is already taken.");
}
}
return View(registerViewModel);
}
2
, , , ?
3
, , submit. - , ?
,