Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

6. Validating with the Validation API > Validating a Single Object on Demand wi...

Validating a Single Object on Demand with GetValidationResult

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 string Description { get; set; }

Note

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 string LastName { 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.


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial