I am new to MVC, I am doing registration form and if you want to register, you have to enter Email that doesn't exist in the DB, and I've put that method in the Controller, is it good to keep methods like that in the Controller or I should move this method into the Model, or implement IValidatableObject?
Asked
Active
Viewed 522 times
1 Answers
2
you should put validation in your ViewModel (or Model) and define your Validation in Model like this :
public class RegisterViewModel
{
public string Name { get; set; }
[Required(ErrorMessage = "please fill Email Address")]
public string Email { get; set; }
[Required(ErrorMessage = "please fill Password")]
public string Password { get; set; }
[Required(ErrorMessage = "please fill ConfirmPassword")]
[Compare("Password", ErrorMessage = "...")]
public string ConfirmPassword { get; set; }
}
and Check Form Validate in your Controller like this :
[HttpPost]
public virtual ActionResult Create(RegisterViewModel registerViewModel)
{
if (!ModelState.IsValid)
return View(registerViewModel);
}
and you can create custome Validation :
Create Custome Validation -Stackoverflow
Custome Validation In MVC-CodeProject
Updated:
If you want check Email is Exists or No , You Can User Remote
Attribute Like this :
[Remote("CheckEmailIsExist", "User","", ErrorMessage = "This Email Address is Exists in database , please use another",HttpMethod = "POST")]
public string Email { get; set; }
in controller :
public virtual JsonResult CheckEmailIsExist(string email)
{
return _userService.ExistsByEmail(email)
? Json(false)
: Json(true);
}
and implement in Service Layer Like this :
public bool ExistsByEmail(string email)
{
return
_users.Any(
user => user.Email== email);
}

Community
- 1
- 1

Uthman Rahimi
- 708
- 5
- 22
-
I have attributes, I need to check email in the database, I have method bool SameEmailNotExist(int id, string email), should I put this method in the Model class? – CrushJelly Jan 18 '16 at 20:34
-
@CrushJelly please see updated answer ! – Uthman Rahimi Jan 19 '16 at 04:56