HTML and CSS Reference
In-Depth Information
<%= Html.Label("Email Address :")%>
</td>
<td width="50%">
<%= Html.TextBox("Email", "", new {type="email"})%>
<%= Html.ValidationMessage("Email","*")%>
</td>
</tr>
</table>
<input id="Submit1" type="submit" value="Submit" />
<%= Html.ValidationSummary() %>
<%}%>
As you can see, the Email text box has its type set to email . Also notice how the ValidationMessage and
ValidationSummary MVC HTML helpers display validation errors. The HTML5 validations happen right in
the browser. However, the MVC validations are performed in a controller, as shown in Listing 5-13.
Listing 5-13. Performing Validations in a Controller
[HttpPost]
public ActionResult Index(FormCollection form)
{
if (form["FirstName"].Length < 3 || form["irstname"].Length > 50)
{
ModelState.AddModelError("FirstName",
"Invalid First Name. Must be between 3 and 50 characters.");
}
if (form["LastName"].Length < 3 || form["LastName"].Length > 50)
{
ModelState.AddModelError("LastName",
"Invalid Last Name. Must be between 3 and 50 characters.");
}
if (form["Email"].Length <= 0)
{
ModelState.AddModelError("Email", "Please enter Email Address.");
}
if(!Regex.IsMatch(form["Email"],@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"))
{
ModelState.AddModelError("Email", "Invalid Email Address.");
}
return View();
}
As you can see, the Index() action method performs validation on the form data and accordingly adds
error messages in the ModelState . The validation helpers display these model errors in the browser (see
Figure 5-15).
 
Search WWH ::




Custom Search