I'm using MVC5 and trying to validate a form.
When I insert an invalid email address on the field, it shows the error message
If I insert a@a (which is a valid email address), the front-end validation pass, but on back end, my ModelState shows an error on the E-mail field, telling that is invalid.
If I insert a@a.com, both validation sides pass!
Note: Great part of the other SO answers related to "email validation not working on MVC", the solution was to use the EmailAddress attribute, which i'm already using.
View
@using (Ajax.BeginForm("EnviarMensagemContato", "home", new AjaxOptions { HttpMethod = "POST", OnBegin = "showLoading", OnComplete = "showJsonModalMessage" }, new { @id = "contact-form" }))
{
@Html.AntiForgeryToken()
<div class="col-md-6 lateral-division">
<div class="form-group">
@Html.TextBoxFor(m => m.ContatoViewModel.Nome, new { @class = "form-control required", placeholder = "nome" })
@Html.ValidationMessageFor(m => m.ContatoViewModel.Nome)
</div>
<div class="form-group">
@Html.TextBoxFor(m => m.ContatoViewModel.EmailAddress, new { @class = "form-control required", placeholder = "email" })
@Html.ValidationMessageFor(m => m.ContatoViewModel.EmailAddress)
</div>
<div class="form-group">
@Html.TextAreaFor(m => m.ContatoViewModel.Mensagem, 4, 4, new { @class = "form-control required", placeholder = "mensagem" })
@Html.ValidationMessageFor(m => m.ContatoViewModel.Mensagem)
</div>
</div>
<div class="btn-group pull-right btn-send-message">
<input type="submit" value="enviar" id="enviar-mensagem" class="btn btn-default" />
</div>
}
Model
public class ContatoViewModel
{
[Required(ErrorMessage="campo obrigatório"),
Display(Name = "nome")]
public String Nome { get; set; }
[Required(ErrorMessage = "campo obrigatório"),
Display(Name = "nome"), MaxLength(254,ErrorMessage="email inválido"),
EmailAddress(ErrorMessage="email inválido")]
public String EmailAddress { get; set; }
[Required(ErrorMessage = "campo obrigatório"),
Display(Name = "nome"), MaxLength(500, ErrorMessage = "maximo de 500 caracteres")]
public String Mensagem { get; set; }
}
Controller
public JsonResult EnviarMensagemContato(ModelContainer model)
{
try
{
if (ModelState.IsValid)
{
//zalgo
}
}
}