Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat's the recommended place to perform validation: ViewModel, Model or Controller?
    primarykey
    data
    text
    <p>I have a registration page and would like to perform some validation (in addition to the StringLength and Required annotations on my ViewModel) for duplicate usernames and email addresses. Currently I perform this validation in my controller when the registration form is posted back. I'm not sure if this is the right place to do it though. </p> <p>I can't imagine the ViewModel to be the right place as it would require the ViewModel to have a reference to my UserRepository. Does it make sense to have this kind of validation in the model classes?</p> <p>If so, how do I implement this on the model so I can check if the information is valid before I sent it into my repository?</p> <p><strong>Update</strong></p> <p>Code of my controller action:</p> <pre><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); } </code></pre> <p><strong>Update 2</strong></p> <p>Should the domain model care about such constraints as duplicate user names or email addresses or is this something that the controller layer should worry about?</p> <p><strong>Update 3</strong></p> <p>It seems that putting the validation logic in the controller makes the most sense as it can be reused in remote validation and in model validation on submit. Is something like checking for duplicates generally a thing that should be done in controllers or does it make sense to have these kind of checks in a domain model?</p> <p>Thanks,</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload