Validations in MVC.

Jun 20 2018 8:13 AM
This is code of view.m trying to add validation in form.by default it shows validation for required field on page load.
<html>
<head>
<style>
td {
padding:20px;
}
</style>
</head>
<body>
@using (Html.BeginForm("Index", "EMP", FormMethod.Post))
{
<table cellpadding="0" cellspacing="0">
<tr>
<th colspan="2" align="center">Employee Details</th>
</tr>
<tr>
<td>EmployeeId: </td>
<td>
@Html.TextBoxFor(m=>m.EmpId)
@Html.ValidationMessageFor(m=>m.EmpId, "", new { @class = "text-danger" })
</td>
</tr>
<tr>
<td>Name: </td>
<td>
@Html.TextBoxFor(m => m.Name)
@Html.ValidationMessageFor(m => m.Name, "", new { @class = "text-danger" })
</td>
</tr>
<tr>
<td>Gender: </td>
<td>
@Html.DropDownListFor(m => m.Gender, new List<SelectListItem>
{ new SelectListItem{Text="Male", Value="M"},
new SelectListItem{Text="Female", Value="F"}}, "Please select")
</td>
</tr>
<tr>
<td>City: </td>
<td>
@Html.TextBoxFor(m => m.City)
@Html.ValidationMessageFor(m => m.City, "", new { @class = "text-danger" })
</td>
</tr>
<tr>
<tr>
<td>City: </td>
<td>
@Html.TextBoxFor(m => m.Email)
@Html.ValidationMessageFor(m => m.Email,"", new { @class = "text-danger" })
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
}
</body>
</html>
Conroller:
public ActionResult Index(Employee emp)
{
int id = emp.EmpId;
string name = emp.Name;
string gender = emp.Gender;
string city = emp.City;
string email = emp.Email;
return View();
}
Model:
public class Employee
{
[Required]
public int EmpId { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Gender { get; set; }
[Required]
public string City { get; set; }
[Required(ErrorMessage = "Email is Required")]
[RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
@".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
ErrorMessage = "Email is not valid")]
public string Email { get; set; }
}
Output:
 

Answers (3)