-
Notifications
You must be signed in to change notification settings - Fork 103
Traduction de cookbook/form-validation.md
#168
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 10 commits
ff724b7
59a6704
559664e
27be772
4f48ed2
b51a1d8
6825579
3b216fe
2303b01
24a39ad
f4f86dd
a330ff9
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
|
@@ -4,11 +4,12 @@ type: cookbook | |||||
order: 3 | ||||||
--- | ||||||
|
||||||
## Base Example | ||||||
## Exemple de base | ||||||
|
||||||
<p>Cette page est en cours de traduction. Pour nous aider, vous pouvez participer sur <a href="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> | ||||||
<p>Cette page est en cours de traduction. Pour nous aider, vous pouvez participer sur <a href="https://github.com/vuejs-fr/vuejs.org" target="_blank">le dépôt GitHub dédié de Vuejs-FR</a>.</p><p> | ||||||
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> | ||||||
|
||||||
Given a form of three fields, make two required. Let's look at the HTML first: | ||||||
Pour un formulaire avec trois champs, considérons que deux sont obligatoires. Regardons le HTML d'abord: | ||||||
|
||||||
``` html | ||||||
<form | ||||||
|
@@ -68,11 +69,11 @@ Given a form of three fields, make two required. Let's look at the HTML first: | |||||
</form> | ||||||
``` | ||||||
|
||||||
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). | ||||||
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). | ||||||
|
||||||
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. | ||||||
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. | ||||||
|
||||||
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. | ||||||
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. | ||||||
|
||||||
``` js | ||||||
const app = new Vue({ | ||||||
|
@@ -104,14 +105,14 @@ const app = new Vue({ | |||||
}) | ||||||
``` | ||||||
|
||||||
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. | ||||||
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. | ||||||
|
||||||
<p data-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 <a href="https://codepen.io/cfjedimaster/pen/GObpZM/">form validation 1</a> by Raymond Camden (<a href="https://codepen.io/cfjedimaster">@cfjedimaster</a>) on <a href="https://codepen.io">CodePen</a>.</p> | ||||||
<p data-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 <a href="https://codepen.io/cfjedimaster/pen/GObpZM/">form validation 1</a> par Raymond Camden (<a href="https://codepen.io/cfjedimaster">@cfjedimaster</a>) sur <a href="https://codepen.io">CodePen</a>.</p> | ||||||
<script async src="https://production-assets.codepen.io/assets/embed/ei.js"></script> | ||||||
|
||||||
## Using Custom Validation | ||||||
## Utiliser une validation personnalisée. | ||||||
|
||||||
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. | ||||||
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. | ||||||
|
||||||
``` html | ||||||
<form | ||||||
|
@@ -172,7 +173,7 @@ For the second example, the second text field (age) was switched to email which | |||||
</form> | ||||||
``` | ||||||
|
||||||
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. | ||||||
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. | ||||||
|
||||||
``` js | ||||||
const app = new Vue({ | ||||||
|
@@ -210,14 +211,14 @@ const app = new Vue({ | |||||
}) | ||||||
``` | ||||||
|
||||||
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: | ||||||
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: | ||||||
|
||||||
<p data-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 <a href="https://codepen.io/cfjedimaster/pen/vWqNXZ/">form validation 2</a> by Raymond Camden (<a href="https://codepen.io/cfjedimaster">@cfjedimaster</a>) on <a href="https://codepen.io">CodePen</a>.</p> | ||||||
<p data-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 <a href="https://codepen.io/cfjedimaster/pen/vWqNXZ/">form validation 2</a> par Raymond Camden (<a href="https://codepen.io/cfjedimaster">@cfjedimaster</a>) sur <a href="https://codepen.io">CodePen</a>.</p> | ||||||
<script async src="https://production-assets.codepen.io/assets/embed/ei.js"></script> | ||||||
|
||||||
## Another Example of Custom Validation | ||||||
## Autre exemple de validation personnalisée | ||||||
|
||||||
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. | ||||||
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. | ||||||
|
||||||
``` html | ||||||
<form | ||||||
|
@@ -283,7 +284,7 @@ For the third example, we've built something you've probably seen in survey apps | |||||
</form> | ||||||
``` | ||||||
|
||||||
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. | ||||||
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. | ||||||
|
||||||
``` js | ||||||
const app = new Vue({ | ||||||
|
@@ -323,14 +324,14 @@ const app = new Vue({ | |||||
}) | ||||||
``` | ||||||
|
||||||
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: | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Il faut éviter les mots comme "simple", "juste", qui peuvent être décourageants pour des débutants qui ne trouvent pas ça simple et intuitif. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @rsp, fait. |
||||||
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: | ||||||
|
||||||
<p data-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 <a href="https://codepen.io/cfjedimaster/pen/vWqGoy/">form validation 3</a> by Raymond Camden (<a href="https://codepen.io/cfjedimaster">@cfjedimaster</a>) on <a href="https://codepen.io">CodePen</a>.</p> | ||||||
<p data-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 <a href="https://codepen.io/cfjedimaster/pen/vWqGoy/">form validation 3</a> par Raymond Camden (<a href="https://codepen.io/cfjedimaster">@cfjedimaster</a>) sur <a href="https://codepen.io">CodePen</a>.</p> | ||||||
<script async src="https://production-assets.codepen.io/assets/embed/ei.js"></script> | ||||||
|
||||||
## Server-side Validation | ||||||
## Validation côté serveur | ||||||
|
||||||
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: | ||||||
Dans mon dernier exemple, nous contruisons quelquechose qui utilise Ajax afin de valider 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. | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. En relisant je trouve l'utilisation de 'quelque chose' et même la phrase un peu lourde. Ne serait-il pas mieux d'écrire:
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Oui c'est effectivement mieux :) There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Quid du coup de ce paragraphe? |
||||||
|
||||||
``` js | ||||||
function main(args) { | ||||||
|
@@ -347,7 +348,7 @@ function main(args) { | |||||
} | ||||||
``` | ||||||
|
||||||
Basically any name but "vista", "empire", and "mbp" are acceptable. Ok, so let's look at the form. | ||||||
En gros, tous les noms excepté "vista", "empire", and "mbp" sont valides. Bien, regardons donc le formulaire. | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||||||
|
||||||
``` html | ||||||
<form | ||||||
|
@@ -383,7 +384,7 @@ Basically any name but "vista", "empire", and "mbp" are acceptable. Ok, so let's | |||||
</form> | ||||||
``` | ||||||
|
||||||
There isn't anything special here. So let's go on to the JavaScript. | ||||||
Il n'y a rien de bien spécial ici. Voyons maintenant le JavaScript. | ||||||
|
||||||
``` js | ||||||
const apiUrl = 'https://openwhisk.ng.bluemix.net/api/v1/web/rcamden%40us.ibm.com_My%20Space/safeToDelete/productName.json?name='; | ||||||
|
@@ -419,14 +420,14 @@ const app = new Vue({ | |||||
}) | ||||||
``` | ||||||
|
||||||
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: | ||||||
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: | ||||||
|
||||||
<p data-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 <a href="https://codepen.io/cfjedimaster/pen/BmgzeM/">form validation 4</a> by Raymond Camden (<a href="https://codepen.io/cfjedimaster">@cfjedimaster</a>) on <a href="https://codepen.io">CodePen</a>.</p> | ||||||
<p data-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 <a href="https://codepen.io/cfjedimaster/pen/BmgzeM/">form validation 4</a> par Raymond Camden (<a href="https://codepen.io/cfjedimaster">@cfjedimaster</a>) sur <a href="https://codepen.io">CodePen</a>.</p> | ||||||
<script async src="https://production-assets.codepen.io/assets/embed/ei.js"></script> | ||||||
|
||||||
## Alternative Patterns | ||||||
## Patterns alternatifs | ||||||
|
||||||
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: | ||||||
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: | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||||||
|
||||||
* [vuelidate](https://github.com/monterail/vuelidate) | ||||||
* [VeeValidate](http://vee-validate.logaretm.com/) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
À supprimer non ?