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.

side validation, such as Required, Range, and StringLength. Listing 25-23 shows the Appointment model<br />

class with these annotations applied. (I have removed the implementation of the IValidatableObject interface, which<br />

has no effect on client-side validation.)<br />

Listing 25-23. Validation Attributes Applied in the Appointment.cs File<br />

using System;<br />

using System.ComponentModel.DataAnnotations;<br />

namespace ModelValidation.Models {<br />

public class Appointment {<br />

[Required]<br />

[StringLength(10, MinimumLength = 3)]<br />

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

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

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

}<br />

}<br />

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

That’s all I have to do to get the basic client-side validation working. I have applied a slightly different mix of the built-in<br />

validation attributes so that I can demonstrate some of the client-side validation features. But once you have the JavaScript libraries<br />

included in the HTML that is sent to the client, everything just starts to work. You can see the effect of the client-side validation<br />

by starting the application, navigating to the /Home/MakeBooking URL and entering the letter X into the name field. Hit<br />

the tab key or click one of the other input elements and you will immediately see a validation message produced by the JavaScript<br />

running in the browser, as shown in Figure 25-11.<br />

Figure 25-11. Immediate feedback from the client-side validation feature<br />

I applied the StringLength validation attribute to the Appointment class in Listing 25-23 and it is the error<br />

message from that attribute that you can see in the figure. The feedback presented in the browser is immediate and no request has<br />

been made to the server. In fact, the JavaScript code that is performing the validation will prevent the form from being submitted<br />

until there are no outstanding validation errors.<br />

685

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

Saved successfully!

Ooh no, something went wrong!