Data annotations

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.

How to do it...

  1. Starting from our previous recipe, let's go to our 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; }
    }
    
  2. Build the project and then reload the form to see the changes. We can already see a neater date (Birth Date) and a text area instead of a textbox (Notes). Submit though, and we start getting feedback as well.
    How to do it...
  3. Validation attributes such as 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.
    How to do it...

How it works...

The default model binder in ASP.NET MVC uses reflection to interrogate target types for attributes that fall under the namespace DataAnnotations. Using the additional metadata provided by the attributes, the model binder can generate a more comprehensive set of tests.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset