在哪里放置自定义验证方法?

时间:2016-01-18 19:45:52

标签: c# asp.net-mvc asp.net-mvc-5

我是MVC的新手,我正在注册表格,如果你想注册,你必须输入数据库中不存在的电子邮件,我已经把这个方法放在了控制器中,这对我来说是好的在Controller中保留类似的方法,或者我应该将此方法移动到模型中,还是实现IValidatableObject?

1 个答案:

答案 0 :(得分:2)

您应该在ViewModel(或模型)中进行验证,并在模型中定义验证,如下所示:

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

并在您的控制器中检查表单验证如下:

 [HttpPost]
    public virtual ActionResult Create(RegisterViewModel registerViewModel)
    {
 if (!ModelState.IsValid)
            return View(registerViewModel);
}

您可以创建自定义验证:

Create Custome Validation -Stackoverflow

Custome Validation In MVC-CodeProject

<强>更新

如果你想检查电子邮件是存在还是否,你可以用户Remote属性像这样:

 [Remote("CheckEmailIsExist", "User","", ErrorMessage = "This Email Address is Exists in database , please use another",HttpMethod = "POST")]
public string Email { get; set; }
控制器中的

 public virtual JsonResult CheckEmailIsExist(string email)
    {
        return _userService.ExistsByEmail(email)
            ? Json(false)
            : Json(true);
    }

并在服务层实现像这样:

 public bool ExistsByEmail(string email)
    {
        return
            _users.Any(
                user => user.Email== email);
    }

Sample of Implement Remote Attribute