Okay, given the minimal effort we put into creating our form, getting that validation message on the birth date was impressive. You would also get an error message if you didn't send a date at all because DateTime
cannot be null.
The question that we will answer in this recipe however, is how do we add validation that is not implied by type? One way is to use data annotations. Data annotations are a collection of attributes that allow you to describe your model in terms of what is required, or what a property might be used for, among other things.
Person
model and make the following amendments:Models/Person.cs: public class Person { [DisplayName("First Name"), StringLength(50)] public string FirstName { get; set; } [DisplayName("Middle Name"), StringLength(50)] public string MiddleName { get; set; } [DisplayName("Last Name"), StringLength(50), Required] public string LastName { get; set; } [DisplayName("Birth Date"), DataType(DataType.Date)] public DateTime BirthDate { get; set; } [DataType(DataType.EmailAddress), Required] public string Email { get; set; } public string Phone { get; set; } public string Postcode { get; set; } [DataType(DataType.MultilineText)] public string Notes { get; set; } }
Required
and StringLength
inherit from ValidationAttribute
, which contains additional properties that allow you to customize the error message or attach the attribute to a resource. In the following screenshot, I've amended the error message of the MiddleName
property.