Validation and Annotation in Practice

Validation exists throughout the development process whether establishing rules in the model class, manipulating views, or tuning controllers. Attributes prove the most simple solution for validation, but the development model may demand field validator controls.

Recall the Sneakers model. Validation applied here establishes a rule (through attributes) used throughout the application leading to less code, errors, and more maintainable code. Review the application of validation attributes to the Sneakers model:

public class Sneakers
	public int ID { get; set; }
	[StringLength(45, MinimumLength = 5)]
	public string Brand { get; set; }
	[Display(Name = "Date of Release")]
	[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}",
ApplyFormatInEditMode = true)]
	public DateTime ReleaseDate { get; set; }
	public string Sport { get; set; }
	[Range(1, 200)]
	public decimal Price { get; set; }
	public string Style { get; set; }

The attributes specify the rules enforced on model properties. The Required attribute demands a value for the property. Length attributes demand a certain number of characters, and the RegularExpression attribute specifies the characteristics of those characters. The Range attribute specifies the acceptable range for values.

These rules automatically impact controllers and views tied to the model. Views and controllers bound to the model acquire validation rules and respond with things like a validation UI characteristic (e.g., red outline on a text field along with an error/requirement message). If using the Sneakers model, the Create action method using a “Sneaker” object as a parameter triggers ASP.NET to spawn the object and map the form input to it. It also, as a part of this mapping process, verifies any validation attributes for the Sneakers object, with ModelState.IsValid returning true on valid input.


The primary validator controls utilized follow:

  1. RequiredFieldValidator – This control ensures input exists in a field. Review its syntax below.
    <asp:RequiredFieldValidator ID="modelnum"
    	runat="server" ControlToValidate ="modelnum"
    	ErrorMessage="Please select a model number"
    	InitialValue="Please select a model number">
  2. RangeValidator – This control ensures input conforms to the specified range. Its properties include Type, MinimumValue, and MaximumValue. Review its syntax below.
    <asp:RangeValidator ID="departmentlvl" runat="server"
    	ErrorMessage="Please enter a department level (1 - 5)"
    MaximumValue="5" MinimumValue="1" Type="Integer">
  3. CompareValidator – This control compares values. Its properties include Type, ControlToCompare, ValueToCompare, and Operator. Review its syntax below.
    <asp:CompareValidator ID="CompareValidator1" runat="server"
  4. RegularExpressionValidator – This control ensures text conforms to a specified pattern. It uses common character escapes, metacharacters, and quantifiers to specify patterns. Review its syntax below.
    <asp:RegularExpressionValidator ID="string" runat="server"
    	ValidationExpression="string" ValidationGroup="string">
  5. CustomValidator – This control allows the developer to implement a routine as a control, which must be supplied through a scripting language. Review its syntax below.
    <asp:CustomValidator ID="MyCustomValidator" runat="server"
  6. ValidationSummary – This control does not validate. It merely presents a summary of all page errors. Its properties include ShowSummary and ShowMessageBox. Review its syntax below.
    <asp:ValidationSummary ID="MyValidationSummary" runat="server"
    	DisplayMode = "BulletList" ShowSummary = "true"
    HeaderText="Errors found:" />

The Data Annotations Model Binder must be downloaded to use annotation validators. Follow software documentation instructions for the particular needs of installation. Note that Microsoft offers no official support for the Model Binder.