Let's say that you have the following class:
public class PersonInfo
{
public int ID { get; set; }
[Display(Name = "First Name")]
[Required(ErrorMessage = "Please enter your first name!")]
public string FirstName{ get; set; }
[Display(Name = "Last Name")]
[Required(ErrorMessage = "Please enter your last name!")]
public string LastName{ get; set; }
[Display(Name = "Age")]
[Required(ErrorMessage = "Please enter your Email Address!")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string EmailAddress { get; set; }
}
These custom error messages will appear if your ModelState.IsValid
returns false.
But, you as well as I know that there can only be 1 email address per person, or else you will be sending emails to potentially wrong people and/or multiple people. This is where checking in the controller comes into play. So let's assume people are creating accounts for you to save via the Create Action.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID, FirstName, LastName, EmailAddress")] PersonInfo newPerson)
{
if(ModelState.IsValid) // this is where the custom error messages on your model will display if return false
{
if(database.People.Any(x => x.EmailAddress == newPerson.EmailAddress)) // checking if the email address that the new person is entering already exists.. if so show this error message
{
ModelState.AddModelError("EmailAddress", "This email address already exists! Please enter a new email address!");
return View(newPerson);
}
db.Person.Add(newPerson);
db.SaveChanges():
return RedirectToAction("Index");
}
return View(newPerson);
}
I hope this is able to help somebody!