Annotating data
The .NET Framework also provides us with an alternative, attribute-based validation system in the System.ComponentModel.DataAnnotations
namespace. It is mostly comprised of a wide range of attribute classes that we can decorate our data model properties with, to specify our validation rules. In addition to these attributes, it also includes a few validation classes, which will investigate later.
As an example, let's look at replicating the current validation rules from our Product
class with these data annotation attributes. We need to validate that the Name
property is entered and has a length of twenty-five characters or less, and that the Price
property is more than zero. For the Name
property, we can use the RequiredAttribute
and the MaxLengthAttribute
.
[Required(ErrorMessage = "Please enter the product name.")] [MaxLength(25, ErrorMessage = "The product name cannot be longer than twenty-five characters.")] public string Name { get { return...