Skip to content

Commit 27e907f

Browse files
authored
Remove unnecessary jQuery document.ready call (dotnet#7899)
Fixes dotnet#7894 Also incorporated a few Acrolinx suggestions while I was in there. [Internal Review Page](https://review.docs.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-2.1&branch=pr-en-us-7899#iclientmodelvalidator)
1 parent d3f8f45 commit 27e907f

File tree

2 files changed

+33
-30
lines changed

2 files changed

+33
-30
lines changed

aspnetcore/mvc/models/validation.md

+12-9
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ title: Model validation in ASP.NET Core MVC
33
author: tdykstra
44
description: Learn about model validation in ASP.NET Core MVC.
55
ms.author: riande
6-
ms.date: 12/18/2016
6+
ms.date: 07/31/2018
77
uid: mvc/models/validation
88
---
99
# Model validation in ASP.NET Core MVC
@@ -112,7 +112,7 @@ You must have a view with the proper JavaScript script references in place for c
112112

113113
[!code-cshtml[](validation/sample/Views/Shared/_ValidationScriptsPartial.cshtml)]
114114

115-
The [jQuery Unobtrusive Validation](https://github.com/aspnet/jquery-validation-unobtrusive) script is a custom Microsoft front-end library that builds on the popular [jQuery Validate](https://jqueryvalidation.org/) plugin. Without jQuery Unobtrusive Validation, you would have to code the same validation logic in two places: once in the server side validation attributes on model properties, and then again in client side scripts (the examples for jQuery Validate's [`validate()`](https://jqueryvalidation.org/validate/) method shows how complex this could become). Instead, MVC's [Tag Helpers](xref:mvc/views/tag-helpers/intro) and [HTML helpers](xref:mvc/views/overview) are able to use the validation attributes and type metadata from model properties to render HTML 5 [data- attributes](http://w3c.github.io/html/dom.html#embedding-custom-non-visible-data-with-the-data-attributes) in the form elements that need validation. MVC generates the `data-` attributes for both built-in and custom attributes. jQuery Unobtrusive Validation then parses thes `data-` attributes and passes the logic to jQuery Validate, effectively "copying" the server side validation logic to the client. You can display validation errors on the client using the relevant tag helpers as shown here:
115+
The [jQuery Unobtrusive Validation](https://github.com/aspnet/jquery-validation-unobtrusive) script is a custom Microsoft front-end library that builds on the popular [jQuery Validate](https://jqueryvalidation.org/) plugin. Without jQuery Unobtrusive Validation, you would have to code the same validation logic in two places: once in the server side validation attributes on model properties, and then again in client side scripts (the examples for jQuery Validate's [`validate()`](https://jqueryvalidation.org/validate/) method shows how complex this could become). Instead, MVC's [Tag Helpers](xref:mvc/views/tag-helpers/intro) and [HTML helpers](xref:mvc/views/overview) are able to use the validation attributes and type metadata from model properties to render HTML 5 [data- attributes](http://w3c.github.io/html/dom.html#embedding-custom-non-visible-data-with-the-data-attributes) in the form elements that need validation. MVC generates the `data-` attributes for both built-in and custom attributes. jQuery Unobtrusive Validation then parses the `data-` attributes and passes the logic to jQuery Validate, effectively "copying" the server side validation logic to the client. You can display validation errors on the client using the relevant tag helpers as shown here:
116116

117117
[!code-cshtml[](validation/sample/Views/Movies/Create.cshtml?highlight=4,5&range=19-25)]
118118

@@ -202,11 +202,11 @@ Attributes that implement this interface can add HTML attributes to generated fi
202202
id="ReleaseDate" name="ReleaseDate" value="" />
203203
```
204204

205-
Unobtrusive validation uses the data in the `data-` attributes to display error messages. However, jQuery doesn't know about rules or messages until you add them to jQuery's `validator` object. This is shown in the example below that adds a method named `classicmovie` containing custom client validation code to the jQuery `validator` object. An explanations of the unobtrusive.adapters.add method can be found [here](http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html)
205+
Unobtrusive validation uses the data in the `data-` attributes to display error messages. However, jQuery doesn't know about rules or messages until you add them to jQuery's `validator` object. This is shown in the following example, which adds a custom `classicmovie` client validation method to the jQuery `validator` object. For an explanation of the `unobtrusive.adapters.add` method, see [Unobtrusive Client Validation in ASP.NET MVC](http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html).
206206

207-
[!code-javascript[](validation/sample/Views/Movies/Create.cshtml?range=71-93)]
207+
[!code-javascript[](validation/sample/Views/Movies/Create.cshtml?name=snippet_UnobtrusiveValidation)]
208208

209-
Now jQuery has the information to execute the custom JavaScript validation as well as the error message to display if that validation code returns false.
209+
With the preceding code, the `classicmovie` method performs client-side validation on the movie release date. The error message displays if the method returns `false`.
210210

211211
## Remote validation
212212

@@ -216,11 +216,14 @@ You can implement remote validation in a two step process. First, you must annot
216216

217217
[!code-csharp[](validation/sample/User.cs?range=7-8)]
218218

219-
The second step is putting the validation code in the corresponding action method as defined in the `[Remote]` attribute. According to the jQuery Validate [`remote()`](https://jqueryvalidation.org/remote-method/) method documentation:
219+
The second step is putting the validation code in the corresponding action method as defined in the `[Remote]` attribute. According to the jQuery Validate [remote](https://jqueryvalidation.org/remote-method/) method documentation, the server response must be a JSON string that's either:
220220

221-
> The serverside response must be a JSON string that must be `"true"` for valid elements, and can be `"false"`, `undefined`, or `null` for invalid elements, using the default error message. If the serverside response is a string, eg. `"That name is already taken, try peter123 instead"`, this string will be displayed as a custom error message in place of the default.
221+
* `"true"` for valid elements.
222+
* `"false"`, `undefined`, or `null` for invalid elements, using the default error message.
222223

223-
The definition of the `VerifyEmail()` method follows these rules, as shown below. It returns a validation error message if the email is taken, or `true` if the email is free, and wraps the result in a `JsonResult` object. The client side can then use the returned value to proceed or display the error if needed.
224+
If the server response is a string (for example, `"That name is already taken, try peter123 instead"`), the string is displayed as a custom error message in place of the default string.
225+
226+
The definition of the `VerifyEmail` method follows these rules, as shown below. It returns a validation error message if the email is taken, or `true` if the email is free, and wraps the result in a `JsonResult` object. The client side can then use the returned value to proceed or display the error if needed.
224227

225228
[!code-csharp[](validation/sample/UsersController.cs?range=19-28)]
226229

@@ -237,7 +240,7 @@ The `AdditionalFields` property of the `[Remote]` attribute is useful for valida
237240
Now when users enter a first and last name, JavaScript:
238241

239242
* Makes a remote call to see if that pair of names has been taken.
240-
* If the pair has been taken, an error message is displayed.
243+
* If the pair has been taken, an error message is displayed.
241244
* If not taken, the user can submit the form.
242245

243246
If you need to validate two or more additional fields with the `[Remote]` attribute, you provide them as a comma-delimited list. For example, to add a `MiddleName` property to the model, set the `[Remote]` attribute as shown in the following code:

aspnetcore/mvc/models/validation/sample/Views/Movies/Create.cshtml

+21-21
Original file line numberDiff line numberDiff line change
@@ -68,28 +68,28 @@
6868
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
6969

7070
<script type="text/javascript">
71-
$(function () {
72-
$.validator.addMethod('classicmovie',
73-
function (value, element, params) {
74-
// Get element value. Classic genre has value '0'.
75-
var genre = $(params[0]).val(),
76-
year = params[1],
77-
date = new Date(value);
78-
if (genre && genre.length > 0 && genre[0] === '0') {
79-
// Since this is a classic movie, invalid if release date is after given year.
80-
return date.getFullYear() <= year;
81-
}
71+
// <snippet_UnobtrusiveValidation>
72+
$.validator.addMethod('classicmovie',
73+
function (value, element, params) {
74+
// Get element value. Classic genre has value '0'.
75+
var genre = $(params[0]).val(),
76+
year = params[1],
77+
date = new Date(value);
78+
if (genre && genre.length > 0 && genre[0] === '0') {
79+
// Since this is a classic movie, invalid if release date is after given year.
80+
return date.getFullYear() <= year;
81+
}
8282
83-
return true;
84-
});
83+
return true;
84+
});
8585
86-
$.validator.unobtrusive.adapters.add('classicmovie',
87-
['year'],
88-
function (options) {
89-
var element = $(options.form).find('select#Genre')[0];
90-
options.rules['classicmovie'] = [element, parseInt(options.params['year'])];
91-
options.messages['classicmovie'] = options.message;
92-
});
93-
});
86+
$.validator.unobtrusive.adapters.add('classicmovie',
87+
['year'],
88+
function (options) {
89+
var element = $(options.form).find('select#Genre')[0];
90+
options.rules['classicmovie'] = [element, parseInt(options.params['year'])];
91+
options.messages['classicmovie'] = options.message;
92+
});
93+
// </snippet_UnobtrusiveValidation>
9494
</script>
9595
}

0 commit comments

Comments
 (0)