I have a layered application, and in my presentation layer, I have a ViewModel
that is UsuarioViewModel
within this I have a property call public email {get; set;}
.
> that is being registered already exists in my database!.
I tried to make a custom validation attribute but without success, my simple question is: How do I validate the server and send the "Email already registered" message in the same way that the Required, Min, Max , Date, CreditCard , understand.
Just a note:
You may wonder why you do not validate by Microsoft jQuery Unobtrusive , my answer is: You may have users who disable the execution of Java Script commands in the browser understand, that's why. p>
Since when the user fills in the email field on the form the controller will give True in my line ModedelState.IsValid
, how do I validate in this case?
UserViewModel.cs :
public class UsuarioViewModel : BaseModel
{
[DisplayName("Código")]
public override int id { get; set; }
[DisplayName("Nome")]
[Required(ErrorMessage = "Informe seu o nome completo")]
public string nomeCompleto { get; set; }
[DisplayName("Login")]
[Required(ErrorMessage = "Informe o login")]
[MinLength(7, ErrorMessage = "O login deve ter 8 ou mais caracteres")]
public string login { get; set; }
[DisplayName("Senha")]
[Required(ErrorMessage = "Informe a senha")]
[MinLength(7, ErrorMessage = "A senha deve ter 8 ou mais caracteres")]
public string senha { get; set; }
[DisplayName("Email")]
[Required(ErrorMessage = "Informe o email")]
[RegularExpression(@"^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$", ErrorMessage = "Informe um email válido")]
public string email { get; set; }
[DisplayName("Chave de Criptgrafia")]
[Required(ErrorMessage = "Informe uma palavra ou frase pquena para chave criptografia")]
public string chaveSimetrica { get; set; }
[DisplayName("Data de Cadastro")]
[Required(ErrorMessage = "Informe a data de cadastro")]
[DataType(DataType.DateTime)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime dataCriacao { get; set; }
[DisplayName("Status")]
[Required(ErrorMessage = "Informe o status")]
public string status { get; set; }
}
UserController.cs :
[System.Web.Mvc.HttpPost]
public ActionResult AdicionaUsuario([Bind(Exclude = "id")] UsuarioViewModel usuarioViewModel)
{
if (!ModelState.IsValid) return View();
Usuario usuario = new Usuario();
SetModel(usuario, usuarioViewModel);
_usuarioService.adicionaUsuario(usuario);
return RedirectToAction("ListaUsuario");
}
[System.Web.Mvc.HttpPost]
public ActionResult EditaUsuario(UsuarioViewModel usuarioViewModel)
{
if (!ModelState.IsValid) return View();
Usuario usuario = new Usuario();
SetModel(usuario, usuarioViewModel);
_usuarioService.editaUsuario(usuario);
return RedirectToAction("ListaUsuario");
}