29.05.2015 Views

o_19mgorv9t13a3ko71fev19l81mqa.pdf

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

}<br />

}<br />

}<br />

This class defines a new attribute that I have called MustBeTrueAttribute and which overrides the IsValid<br />

method of the base class. This is the method that the model binder will call to validate properties to which the attribute is applied,<br />

passing in the value that the user has provided as the parameter.<br />

The validation logic is simple; a value is valid if it is a bool that has a value of true. I indicate that a value is valid by<br />

returning true from the IsValid method. In Listing 25-14, you can see how I have replaced the Range attribute with the<br />

custom MustBeTrue attribute in the Appointment class.<br />

Listing 25-14. Applying a Custom Validation Attribute in the Appointment.cs File<br />

using System;<br />

using System.ComponentModel.DataAnnotations;<br />

using ModelValidation.Infrastructure;<br />

namespace ModelValidation.Models {<br />

public class Appointment {<br />

[Required]<br />

public string ClientName { get; set; }<br />

[DataType(DataType.Date)]<br />

[Required(ErrorMessage="Please enter a date")]<br />

public DateTime Date { get; set; }<br />

}<br />

}<br />

[MustBeTrue(ErrorMessage="You must accept the terms")]<br />

public bool TermsAccepted { get; set; }<br />

This is neater and easier to make sense of than abusing the Range attribute. You can see the effect of the custom model<br />

validation attribute in Figure 25-8.<br />

677

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!