Dataannotation: How to validate "e-mail" property, check whether or not it exists in the database, with attribute other than in the client and yes in the Server

Asked

Viewed 1,692 times

2

I have a layered application, and in my presentation layer, I have a ViewModel that is UsuarioViewModel inside this I have a Property calling for public email {get; set;}.

Already this validating through Dataannotation everything correctly, I need to solve a question, as I validated, without being in the client yes on the server, if the e-mail 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 I validate on the server and send the "Already registered email" message in the same way that already exists the attributes Required, Min, Max, Date, Creditcard, you know what I mean.

Just one observation:

Maybe you wonder why you don’t do the validation by Microsoft jQuery Unobtrusive, my answer is: It may have users who disable the execution of Java Script commands in the browser understand, that’s why.

Since when the user fills the email field in the form the controller will give as True in my line ModedelState.IsValid, as I stand in this case?

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

}

Usuariocontroller.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");
    }

1 answer

2


In order for the Asp net mvc to validate the client I use a System.ComponentModel.Dataannotations.Emailaddressattribute attribute above the email field. So mvc already creates validation in the client. See the example below.

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

Follow the code I put in the view form 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 control onBlur event or. jquery file by passing the email and validating on the server. If the email is already registered you display a message informing. This is the way that gives better usability to the system. 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

  • Very Cool worked!!!! yes... Marco... Fight for the tip!!!

  • @Rodrigo take a look at a post I did on my blog and see that you have an interesting technique in validating email or other attribute on the server side simply called remote validation http://blogdoquintal.net/2015/01/06/fazendo-validaca-ajax-no-servor-com-asp-net-mvc/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.