-3

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?

tereško
  • 58,060
  • 25
  • 98
  • 150
CrushJelly
  • 47
  • 1
  • 9

1 Answers1

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);
    }

Sample of Implement Remote Attribute

Community
  • 1
  • 1
Uthman Rahimi
  • 708
  • 5
  • 22