The goal
Show custom errors on the View using jQuery Validation.
The problem
Everything is working well. Yes... Everything! What I need is a light to a problem. I've already searched on Google and Stack but until now, no success.
Okay, lets go: my log in form composed by email and password is validating well — it throws a message if the email is invalid or if the password field is empty. But what I need is: throw a message if email + password combination doesn't exist on database, or, in other words, if the user doesn't exist.
Take a look in the following fragment:
[...]
[AcceptVerbs(HttpVerbs.Post)]
[ValidateAntiForgeryToken]
[AllowAnonymous]
public ActionResult Authenticate(User userModel)
{
if (ModelState.IsValid)
{
if (userModel.IsValid(userModel.Email, userModel.Password))
{
FormsAuthentication.SetAuthCookie(userModel.Email, userModel.Remember);
return RedirectToAction("Index");
}
else
{
ModelState.AddModelError(String.Empty, "Login data is incorrect!");
}
}
return View(userModel);
}
[...]
Pay attention at this line:
ModelState.AddModelError(String.Empty, "Login data is incorrect!");
I want to display in the view "Login data is incorrect!
" but I do not know how I can do this.
Code spotlight
I'm using jQuery Validation Unobtrusive and that's it — nothing more. I just called the script and the application goes on.
By the way, if necessary, follow some markup:
[...]
@using (Ajax.BeginForm("Authenticate", "Manager",
new AjaxOptions{ HttpMethod = "Post" })){
<ul>
<li>
@Html.LabelFor(m => m.Email, "What's your email?")
@Html.TextBoxFor(m => m.Email, "", new { placeholder = "Email" })
@Html.ValidationMessageFor(m => m.Email)
</li>
<li>
@Html.LabelFor(m => m.Password, "What's your password?")
@Html.TextBoxFor(m => m.Password, "", new { placeholder = "Password" })
@Html.ValidationMessageFor(m => m.Password)
</li>
<li>
@Html.CheckBoxFor(m => m.Remember)
Remember
</li>
<li>
<button type="submit" class="btn btn-primary">Log In</button>
</li>
</ul>
}
[...]
To remember
I just call for the jQuery Validation's scripts and the (simple) validation that I marked as annotation at the top of the properties on model works like magic.
To improve the question comprehension, follow a sneak peak through User
's model:
[...]
[Required]
[EmailAddress]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[...]