29.05.2015 Views

o_19mgorv9t13a3ko71fev19l81mqa.pdf

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Both of these settings must be true for client-side validation to work. When you first created your MVC project, Visual<br />

Studio created these entries and set them to true.<br />

Tip You can also configure client-side validation on a per-view basis by setting the HtmlHelper.<br />

ClientValidationEnabled and HtmlHelper.UnobtrusiveJavaScriptEnabled in a Razor code<br />

block.<br />

Adding the NuGet Packages<br />

Ensuring that the MVC Framework will generate the attributes required for validation is only part of the setup process. I also have<br />

to add the JavaScript packages that process those attributes and check the data that the user has entered into the form. All of the<br />

required packages are available through NuGet, so select Package Manager Console from the Visual Studio<br />

Tools Library Package Manager menu and enter the following commands:<br />

Install-Package jQuery –version 1.10.2<br />

Install-Package jQuery.Validation –version 1.11.1<br />

Install-Package Microsoft.jQuery.Unobtrusive.Validation –version 3.0.0<br />

These packages add files to the Scripts folder, which I then need to add to the layout with script elements, as shown<br />

in Listing 25-22.<br />

Listing 25-22. Adding Script Elements for the Validation Libraries to the _Layout.cshtml File<br />

<br />

<br />

<br />

<br />

<br />

@ViewBag.Title<br />

<br />

.field-validation-error { color: #f00;}<br />

.validation-summary-errors { color: #f00; font-weight: bold;}<br />

.input-validation-error { border: 2px solid #f00; backgroundcolor:<br />

#fee; }<br />

input[type="checkbox"].input-validation-error { outline: 2px solid<br />

#f00; }<br />

<br />

<br />

<br />

<br />

<br />

<br />

@RenderBody()<br />

<br />

<br />

Tip In Chapter 26, I’ll show you the bundles feature, which makes it easier to manage JavaScript and CSS files in a project.<br />

The order in which the script elements are added to the layout is important. You must add the jQuery library first, followed<br />

by the jQuery Validation library and only then can you add the Microsoft unobtrusive validation library.<br />

Using Client-Side Validation<br />

Once I have enabled client-side validation and ensured that the JavaScript libraries are referenced in the layout, I can start to<br />

perform client-side validation. The simplest way of doing this is to apply the metadata attributes that I previously used for server-<br />

684

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

Saved successfully!

Ooh no, something went wrong!