You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/v2/cookbook/form-validation.md
+27-26Lines changed: 27 additions & 26 deletions
Original file line number
Diff line number
Diff line change
@@ -4,11 +4,12 @@ type: cookbook
4
4
order: 3
5
5
---
6
6
7
-
## Base Example
7
+
## Exemple de base
8
8
9
-
<p>Cette page est en cours de traduction. Pour nous aider, vous pouvez participer sur <ahref="https://github.com/vuejs-fr/vuejs.org"target="_blank">le dépôt GitHub dédié de Vuejs-FR</a>.</p><p>Form validation is natively supported by the browser, but sometimes different browsers will handle things in a manner which makes relying on it a bit tricky. Even when validation is supported perfectly, there may be times when custom validations are needed and a more manual, Vue-based solution may be more appropriate. Let's begin with a simple example.</p>
9
+
<p>
10
+
La validation des formulaires est supportée nativement par le navigateur. Parfois on va observer des différences sur la manière de gérer la validation en fonction des navigateurs ce qui fait que se reposer sur cette validation supportée nativement est des plus délicat. Même quand la validation est supportée parfaitement, il se peut que quand des validations personnalisées ou plus "manuelles" sont nécessaires, les solutions basées sur Vue soient plus appropriées. Commençons avec un exemple simple.</p>
10
11
11
-
Given a form of three fields, make two required. Let's look at the HTML first:
12
+
Pour un formulaire avec trois champs, considérons que deux sont obligatoires. Regardons le HTML d'abord:
12
13
13
14
```html
14
15
<form
@@ -68,11 +69,11 @@ Given a form of three fields, make two required. Let's look at the HTML first:
68
69
</form>
69
70
```
70
71
71
-
Let's cover it from the top. The `<form>`tag has an ID that we'll be using for the Vue component. There's a submit handler that you'll see in a bit, and the`action`is a temporary URL that would point to something real on a server someplace (where you have backup server-side validation of course).
72
+
Analysons cela à partir en partant du haut. La balise `<form>`a un id que nous utiliserons pour le composant Vue. Il y a un gestionnaire d'évènement à la soumission du formulaire que vous verrez dans un moment, et l'attribut`action`correspond a une URL temporaire qui devrait pointer vers quelque chose de réel sur un serveur (sur lequel vous avez une validation côté serveur bien entendu).
72
73
73
-
Beneath that there is a paragraph that shows or hides itself based on an error state. This will render a simple list of errors on top of the form. Also note we fire the validation on submit rather than as every field is modified.
74
+
En dessous il y a un paragraphe qui s'affiche ou non en fonction de la présence d'erreurs. C'est une simple liste d'erreurs au-dessus du formulaire. Notez aussi que l'on déclenche la validation à la soumission du formulaire plutôt qu'a la modification de chaque champ.
74
75
75
-
The final thing to note is that each of the three fields has a corresponding `v-model`to connect them to values we will work with in the JavaScript. Now let's look at that.
76
+
La dernière chose à remarquer est que chacun des trois champs possède un `v-model`correspondant afin de les connecter aux valeurs sur lesquelles nous travaillerons en JavaScript.
76
77
77
78
```js
78
79
constapp=newVue({
@@ -104,14 +105,14 @@ const app = new Vue({
104
105
})
105
106
```
106
107
107
-
Fairly short and simple. We define an array to hold errors and set `null` values for the three form fields. The `checkForm`logic (which is run on submit remember) checks for name and age only as movie is optional. If they are empty we check each and set a specific error for each. And that's really it. You can run the demo below. Don't forget that on a successful submission it's going to POST to a temporary URL.
108
+
Relativement court et simple, on définit un tableau pour contenir les erreurs et les valeurs des trois champs du formulaire sont initialisées à `null`. La logique de `checkForm`(qui est activée à la soumission du formulaire) vérifie seulement que name et age ont des valeurs puisque movie est optionnel. Si ce n'est pas le cas, on vérifie chacune d'elles et on ajoute une erreur spécifique quand elles sont nulles. Et c'est tout. Vous pouvez lancer la démo ci-dessous. N'oubliez pas que pour une soumission réussie, cela va générer une requête POST à une URL temporaire.
108
109
109
-
<pdata-height="265"data-theme-id="0"data-slug-hash="GObpZM"data-default-tab="html,result"data-user="cfjedimaster"data-embed-version="2"data-pen-title="form validation 1"class="codepen">See the Pen <ahref="https://codepen.io/cfjedimaster/pen/GObpZM/">form validation 1</a> by Raymond Camden (<ahref="https://codepen.io/cfjedimaster">@cfjedimaster</a>) on <ahref="https://codepen.io">CodePen</a>.</p>
110
+
<pdata-height="265"data-theme-id="0"data-slug-hash="GObpZM"data-default-tab="html,result"data-user="cfjedimaster"data-embed-version="2"data-pen-title="form validation 1"class="codepen">Voir le Pen <ahref="https://codepen.io/cfjedimaster/pen/GObpZM/">form validation 1</a> par Raymond Camden (<ahref="https://codepen.io/cfjedimaster">@cfjedimaster</a>) sur <ahref="https://codepen.io">CodePen</a>.</p>
For the second example, the second text field (age) was switched to email which will be validated with a bit of custom logic. The code is taken from the StackOverflow question, [How to validate email address in JavaScript?](https://stackoverflow.com/questions/46155/how-to-validate-email-address-in-javascript). This is an awesome question because it makes your most intense Facebook political/religious argument look like a slight disagreement over who makes the best beer. Seriously - it's insane. Here is the HTML, even though it's really close to the first example.
115
+
Pour le second exemple, le deuxième champ de texte (age) est remplacé par un champ d'email qui sera validé par un peu de logique personnalisée. Le code vient de la question StackOverflow , [Comment valider une adresse email en JavaScript?](https://stackoverflow.com/questions/46155/how-to-validate-email-address-in-javascript). C'est une très bonne question puisqu'elle fait passer votre plus intense discussion politique ou religieuse sur Facebook pour un simple désaccord sur qui fait la meilleure bière. Sérieusement, c'est délirant. Voici le HTML, même si il est très proche du premier exemple.
115
116
116
117
```html
117
118
<form
@@ -172,7 +173,7 @@ For the second example, the second text field (age) was switched to email which
172
173
</form>
173
174
```
174
175
175
-
While the change here is small, note the`novalidate="true"`on top. This is important because the browser will attempt to validate the email address in the field when `type="email"`. Frankly it may make more sense to trust the browser in this case, but as we wanted an example with custom validation, we're disabling it. Here's the updated JavaScript.
176
+
Bien qu'il y ait peu de différence, remarquez le`novalidate="true"`au début. C'est important car le navigateur va essayer de valider l'adresse email dans le champ quand `type=email` est spécifié. Honnêtement, il est plus logique de faire confiance au navigateur dans ce cas, mais comme nous voulions un exemple personnalisé de validation, nous le désactivons. Voici le JavaScript mis à jour.
176
177
177
178
```js
178
179
constapp=newVue({
@@ -210,14 +211,14 @@ const app = new Vue({
210
211
})
211
212
```
212
213
213
-
As you can see, we've added `validEmail` as a new method and it is simply called from `checkForm`. You can play with this example here:
214
+
Comme vous pouvez le voir, nous avons ajouté une nouvelle méthode `validEmail` qui est simplement appelée par `checkForm`. Vous pouvez jouer avec l'exemple ici:
214
215
215
-
<pdata-height="265"data-theme-id="0"data-slug-hash="vWqNXZ"data-default-tab="html,result"data-user="cfjedimaster"data-embed-version="2"data-pen-title="form validation 2"class="codepen">See the Pen <ahref="https://codepen.io/cfjedimaster/pen/vWqNXZ/">form validation 2</a> by Raymond Camden (<ahref="https://codepen.io/cfjedimaster">@cfjedimaster</a>) on <ahref="https://codepen.io">CodePen</a>.</p>
216
+
<pdata-height="265"data-theme-id="0"data-slug-hash="vWqNXZ"data-default-tab="html,result"data-user="cfjedimaster"data-embed-version="2"data-pen-title="form validation 2"class="codepen">Voir le Pen <ahref="https://codepen.io/cfjedimaster/pen/vWqNXZ/">form validation 2</a> par Raymond Camden (<ahref="https://codepen.io/cfjedimaster">@cfjedimaster</a>) sur <ahref="https://codepen.io">CodePen</a>.</p>
For the third example, we've built something you've probably seen in survey apps. The user is asked to spend a "budget" for a set of features for a new Star Destroyer model. The total must equal 100. First, the HTML.
221
+
Pour le troisième exemple, nous avons construit quelque chose que vous avez surement déjà vu dans des applications de sondage. L'utilisateur se voit demander de dépenser un budget pour un ensemble de propriétés pour un nouveau modèle de Star Destroyer. Le total doit être de 100. Tout d'abord le HTML.
221
222
222
223
```html
223
224
<form
@@ -283,7 +284,7 @@ For the third example, we've built something you've probably seen in survey apps
283
284
</form>
284
285
```
285
286
286
-
Note the set of inputs covering the five different features. Note the addition of `.number`to the `v-model` attribute. This tells Vue to cast the value to a number when you use it. However, there is a bug with this feature such that when the value is blank, it turns back into a string. You'll see the workaround below. To make it a bit easier for the user, we also added a current total right below so they can see, in real time, what their total is. Now let's look at the JavaScript.
287
+
Notez l'ensemble des champs pour les cinq propriétés. Remarquez l'ajout de `.number`à la suite de l'attribut `v-model`. Cela dit à Vue de caster la valeur en un nombre quand vous l'utilisez. Il y a cependant un bug avec cette fonctionnalité qui fait que quand la valeur est nulle, cela retourne une chaine de caractère. Vous verrez comment contourner cela plus bas. Pour faciliter la tâche à l'utilisateur, nous avons ajouté le total en cours juste en bas afin qu'ils puissent le visualiser en temps réel. Maintenant regardons le JavaScript.
287
288
288
289
```js
289
290
constapp=newVue({
@@ -323,14 +324,14 @@ const app = new Vue({
323
324
})
324
325
```
325
326
326
-
We set up the total value as a computed value, and outside of that bug I ran into, it was simple enough to setup. My checkForm method now just needs to see if the total is 100 and that's it. You can play with this here:
327
+
Nous avons défini le total comme une valeur calculée et la méthode checkForm doit maintenant juste vérifier si le total est 100 et c'est tout. Vous pouvez jouer avec ici:
327
328
328
-
<pdata-height="265"data-theme-id="0"data-slug-hash="vWqGoy"data-default-tab="html,result"data-user="cfjedimaster"data-embed-version="2"data-pen-title="form validation 3"class="codepen">See the Pen <ahref="https://codepen.io/cfjedimaster/pen/vWqGoy/">form validation 3</a> by Raymond Camden (<ahref="https://codepen.io/cfjedimaster">@cfjedimaster</a>) on <ahref="https://codepen.io">CodePen</a>.</p>
329
+
<pdata-height="265"data-theme-id="0"data-slug-hash="vWqGoy"data-default-tab="html,result"data-user="cfjedimaster"data-embed-version="2"data-pen-title="form validation 3"class="codepen">Voir le Pen <ahref="https://codepen.io/cfjedimaster/pen/vWqGoy/">form validation 3</a> par Raymond Camden (<ahref="https://codepen.io/cfjedimaster">@cfjedimaster</a>) sur <ahref="https://codepen.io">CodePen</a>.</p>
In my final example, we built something that makes use of Ajax to validate at the server. The form will ask you to name a new product and will then check to ensure that the name is unique. We wrote a quick [OpenWhisk](http://openwhisk.apache.org/)serverless action to do the validation. While it isn't terribly important, here is the logic:
334
+
Dans mon dernier exemple, nous allons construire une application vuejs qui utilise Ajax pour valider des données via le serveur. Le formulaire va vous demander de nommer un nouveau produit et ensuite s'assurer que ce nom est unique. Nous avons écrit une rapide [OpenWhisk](http://openwhisk.apache.org/) action sans serveur pour gérer la validation, voici la logique de cette action.
334
335
335
336
```js
336
337
functionmain(args) {
@@ -347,7 +348,7 @@ function main(args) {
347
348
}
348
349
```
349
350
350
-
Basically any name but "vista", "empire", and "mbp" are acceptable. Ok, so let's look at the form.
351
+
En gros, tous les noms exceptés "vista", "empire", and "mbp" sont valides. Bien, regardons donc le formulaire.
351
352
352
353
```html
353
354
<form
@@ -383,7 +384,7 @@ Basically any name but "vista", "empire", and "mbp" are acceptable. Ok, so let's
383
384
</form>
384
385
```
385
386
386
-
There isn't anything special here. So let's go on to the JavaScript.
387
+
Il n'y a rien de bien spécial ici. Voyons maintenant le JavaScript.
We start off with a variable representing the URL of the API that is running on OpenWhisk. Now look at `checkForm`. In this version, we always prevent the form from submitting (which, by the way, could be done in the HTML with Vue as well). You can see a basic check on `this.name`being empty, and then we hit the API. If it's bad, we add an error as before. If it's good, right now we do nothing (just an alert), but you could navigate the user to a new page with the product name in the URL, or do other actions as well. You can run this demo below:
423
+
On commence par une variable pour l'URL de l'API qui est exécuté sur OpenWhisk. Maintenant, voyons `checkForm`. Dans cette version, nous empêchons le formulaire d'être soumis (ce qui, par ailleurs, pourrait être fait en HTML par Vue). Vous pouvez voir une vérification basique sur la nullité de `this.name`puis on attaque l'API. Si c'est un mauvais nom, on ajoute une erreur comme précédemment. Si c'est bon, dans cet exemple nous ne faisons rien à part une alerte JavaScript, mais vous pouvez renvoyer l'utilisateur vers une nouvelle page avec le nom du produit dans l'URL, ou effectuer d'autres actions. Vous pouvez tester la démo ci-dessous:
423
424
424
-
<pdata-height="265"data-theme-id="0"data-slug-hash="BmgzeM"data-default-tab="js,result"data-user="cfjedimaster"data-embed-version="2"data-pen-title="form validation 4"class="codepen">See the Pen <ahref="https://codepen.io/cfjedimaster/pen/BmgzeM/">form validation 4</a> by Raymond Camden (<ahref="https://codepen.io/cfjedimaster">@cfjedimaster</a>) on <ahref="https://codepen.io">CodePen</a>.</p>
425
+
<pdata-height="265"data-theme-id="0"data-slug-hash="BmgzeM"data-default-tab="js,result"data-user="cfjedimaster"data-embed-version="2"data-pen-title="form validation 4"class="codepen">Voir le Pen <ahref="https://codepen.io/cfjedimaster/pen/BmgzeM/">form validation 4</a> par Raymond Camden (<ahref="https://codepen.io/cfjedimaster">@cfjedimaster</a>) sur <ahref="https://codepen.io">CodePen</a>.</p>
While this cookbook entry focused on doing form validation "by hand", there are, of course, some great Vue libraries that will handle a lot of this for you. Switching to a prepackage library may impact the final size of your application, but the benefits could be tremendous. You have code that is (most likely) heavily tested and also updated on a regular basis. Some examples of form validation libraries for Vue include:
430
+
Bien que cette partie se focalise essentiellement sur une validation "manuelle", il y a bien sûr, de très bonnes bibliothèques permettant de gérer cela pour vous. Opter pour une bibliothèque pré-packagée pourrait avoir un impact sur la taille finale de votre application, mais les bénéfices pourraient être énormes. Vous avez à votre disposition du code qui est (très probablement) très bien testé et aussi mis à jour régulièrement. Quelques exemples de bibliothèques de validation pour Vue:
0 commit comments