Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Our sample classes already have some attributes that will be checked
by the Validation API. For example, in the Destination class, you should already have a
MaxLength annotation on the Description property shown here:
[MaxLength(500)]public stringDescription {get;set; }
Refer to the listing for Destination shown in Example 2-1.
Testing this rule won’t be very easy since breaking it would mean
adding a string that is greater than 500 characters. I don’t feel like
typing that much. Instead, I’ll add a new MaxLength annotation to another property—the
LastName property in the Person class:
[MaxLength(10)]public stringLastName {get;set; }
Now let’s see what happens when we set the length to a string with
more than ten characters. GetValidationResult allows you to explicitly
validate a single entity. It returns a ValidationResult type that contains three
important members. We’ll focus on just one of those for now, the IsValid property, which is a Boolean that
indicates if the instance passed its validation rules. Let’s use that to
validate a Person instance. The
ValidateNewPerson method in Example 6-1 shows calling the
GetValidationResult.IsValid
method.