Validation in Asp.net MVC
Create a new record in MVC (Create.aspx)
This article contain validation for
Empty values
Email validation
PhoneNo validation
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(tblCustomer customer)
{
if (customer.Name.Trim().Length == 0)
ModelState.AddModelError(”Name”, “First name is required.”);
if (!Regex.IsMatch(customer.PhoneNo, @”\b\d{7}”))
ModelState.AddModelError(”PhoneNo”, “Invalid phone number.”);
if (!Regex.IsMatch(customer.EmailID, @”^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$”))
ModelState.AddModelError(”EmailID”, “Invalid email address.”);
if (!ModelState.IsValid)
return View();
try
{
//TODO: Add insert logic here
customerRepository.Add(customer);
customerRepository.Save();
return RedirectToAction(”Details”, new { id = customer.CustomerID });
}
catch
{
return View();
}
}
To match a date in mm/dd/yyyy format, rearrange the regular expression to (0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d. For dd-mm-yyyy format, use (0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d
