DataAnnotation: How to validate "e-mail" property, check whether or not it exists in the database, with attribute not being in the client but in the Server

2

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");
    }
    
asked by anonymous 05.01.2015 / 21:39

1 answer

2

For asp net mvc to validate on the client I use an attribute of type System.ComponentModel.DataAnnotations.EmailAddressAttribute on top of the email field. So mvc already creates validation on the client. See the example below.

    [EmailAddress(ErrorMessage="email invalido")]
    public string email { get; set; }

Follow the code that I put in the form of the view to validate

    @Html.EditorFor(model => model.email, new { htmlAttributes = new { @class = "form-control" } })
    @Html.ValidationMessageFor(model => model.email, "", new { @class = "text-danger" })

Already to validate on the server you have the option to validate with some ajax call triggered in the event onBlur of the control or .blur of jquery passing the email and validating in the server. If the email is already registered, you will see a message informing. This is the way to give the system a better usability. But if you want to validate on the server only when the form is submitted (easier way), you can use the following code

        [HttpPost]
    public ActionResult Index(modelo mod)
    {
        if (ModelState.IsValid)
        {
            // valide aqui o email e mande de volta o erro através da linha abaixo
            ModelState.AddModelError("email", "Email já cadastrado");

        }
        return View();
    }

Note: I used mvc 5 for the example

    
05.01.2015 / 22:14