Using Asp.net MVC validation is very easy in strongly typed but if you have a view that is not strongly typed, you can still do it easily.
Suppose you have following action in controller.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Login(string userEmail, string password)
{
if (ValidateLogin(userEmail, password))
{
//redirect
}
return View();
}
and your validation method looks like,
private bool ValidateLogin(string userEmail, string password)
{
if (String.IsNullOrEmpty(userEmail))
{
ModelState.AddModelError("username", "You must specify a username.");
}
if (password == null || password.Length == 0)
{
ModelState.AddModelError("password",
String.Format(CultureInfo.CurrentCulture,
"You must specify a password."));
}
return ModelState.IsValid;
}
Now in your view, in this case login.aspx in your views folder, you can show your validation in this way.
<label for="useremail">User Email:</label>
<%= Html.TextBox("useremail") %>
<%= Html.ValidationMessage("useremail")%>
Beside this, you can also show validation summary or just show a generic method by using the following helper method.
<%= Html.ValidationSummary(true, "Please correct the errors.") %>