This is code of view.m trying to add validation in form.by default it shows validation for required field on page load.
td {
padding:20px;
}
@using (Html.BeginForm("Index", "EMP", FormMethod.Post))
{
| Employee Details | |||
|---|---|---|---|
| EmployeeId: | @Html.TextBoxFor(m=>m.EmpId) @Html.ValidationMessageFor(m=>m.EmpId, "", new { @class = "text-danger" }) | ||
| Name: | @Html.TextBoxFor(m => m.Name) @Html.ValidationMessageFor(m => m.Name, "", new { @class = "text-danger" }) | ||
| Gender: | @Html.DropDownListFor(m => m.Gender, new List { new SelectListItem{Text="Male", Value="M"}, new SelectListItem{Text="Female", Value="F"}}, "Please select") | ||
| City: | @Html.TextBoxFor(m => m.City) @Html.ValidationMessageFor(m => m.City, "", new { @class = "text-danger" }) | ||
| City: | @Html.TextBoxFor(m => m.Email) @Html.ValidationMessageFor(m => m.Email,"", new { @class = "text-danger" }) | ||
}
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:
Kalyani ShevalePosted Jun 26, 2018, 1:27 AM
Er Kajal KhetiyaPosted Jun 20, 2018, 8:21 AM
Er Kajal KhetiyaPosted Jun 20, 2018, 8:19 AM