Skip to content

Commit 871187b

Browse files
authored
Translated cookbook/form-validation.md (#688)
* translated cookbook/form-validation.md * Update form-validation.md
1 parent 84eb552 commit 871187b

File tree

1 file changed

+28
-29
lines changed

1 file changed

+28
-29
lines changed

src/v2/cookbook/form-validation.md

Lines changed: 28 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
---
2-
title: Form Validation
2+
title: 表单校验
33
type: cookbook
44
order: 3
55
---
66

7-
## Simple Example
7+
## 简单的示例
88

9-
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.
9+
表单校验是浏览器原生支持的,但是有的时候用不同的浏览器处理起来需要一些小技巧。即使当表单校验已经被完美支持,你也还是有很多时候需要进行自定义的校验。这时一个更加手动的基于 Vue 的解决方案可能会更适合。我们来看一个简单的示例。
1010

11-
Given a form of three fields, make two required. Let's look at the HTML first:
11+
给定一个表单,包含三个字段,其中两个是必填项。我们先来看看 HTML
1212

1313
``` html
1414
<form id="app" @submit="checkForm" action="https://vuejs.org/" method="post">
@@ -46,11 +46,11 @@ Given a form of three fields, make two required. Let's look at the HTML first:
4646
</form>
4747
```
4848

49-
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).
49+
我们从头到尾看一遍,这个 `<form>` 标记上有一个我们将会用在 Vue 组件上的 ID。这里有一个你稍后会看到的 `submit` 处理函数,而这里的 `action` 是一个可能指向了某个真实服务器的临时 URL (当然你在服务端也要是有校验的)。
5050

51-
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.
51+
下面有一段内容,会根据错误状态进行显示或隐藏。它将会在表单的最顶端渲染一个简单的错误列表。同时要注意我们会在提交的时候进行校验,而不是每个字段被修改的时候。
5252

53-
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.
53+
最后值得注意的是这三个字段都有一个对应的 `v-model` 来连接它们的值,我们将会在 JavaScript 中使用它。现在我们就来看一下。
5454

5555
``` js
5656
const app = new Vue({
@@ -73,14 +73,14 @@ const app = new Vue({
7373
})
7474
```
7575

76-
Fairly short and simple. We default 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.
76+
非常短小精悍。我们定义了一个数组来放置错误,并将这三个表单字段的默认值设为 `null``checkForm` 的逻辑 (在表单提交时运行) 只会检查姓名和年龄,因为电影时选填的。如果它们是空的,那么我们会检查每一个字段并设置相应的错误,差不多就是这样。你可以在下面运行这个 demo。不要忘记提交成功时它会 POST 到一个临时的 URL
7777

78-
<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>
78+
<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"><a href="https://codepen.io">CodePen</a> 查看 Raymond Camden (<a href="https://codepen.io/cfjedimaster">@cfjedimaster</a>) <a href="https://codepen.io/cfjedimaster/pen/GObpZM/">表单校验 1</a></p>
7979
<script async src="https://production-assets.codepen.io/assets/embed/ei.js"></script>
8080

81-
## Using Custom Validation
81+
## 使用自定义校验
8282

83-
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.
83+
对于第二个示例来说,第二个文本字段 (年龄) 变换成了电子邮件地址,它将会通过一些自定义的逻辑来校验。这部分代码来自 StackOverflow 的问题:[如何在 JavaScript 中校验电子邮件地址](https://stackoverflow.com/questions/46155/how-to-validate-email-address-in-javascript)。这是一个很好的问题,因为它会让 Facebook 上最激烈的政治、宗教争论看上去都只是“哪家的啤酒最好喝”这样的小分歧了。讲真的这很疯狂。我们来看 HTML,尽管它和第一个例子很接近。
8484

8585
``` html
8686
<form id="app" @submit="checkForm" action="https://vuejs.org/" method="post" novalidate="true">
@@ -118,7 +118,7 @@ For the second example, the second text field (age) was switched to email which
118118
</form>
119119
```
120120

121-
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.
121+
尽管这里的不同点很小,注意顶端的 `novalidate="true"`。但是这很重要,因为浏览器会尝试在 `type="email"` 的字端校验邮件地址。坦白说在这个案例中浏览器的校验规则是值得信任的,不过我们想要创建一个自定义校验的例子,所以把它禁用了。以下是更新后的 JavaScript
122122

123123
``` js
124124
const app = new Vue({
@@ -149,14 +149,14 @@ const app = new Vue({
149149
})
150150
```
151151

152-
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:
152+
如你所见,我们添加了一个新方法 `validEmail`,它将会在 `checkForm` 中被调用了。我们现在可以这样运行示例:
153153

154-
<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>
154+
<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"><a href="https://codepen.io">CodePen</a> 查看 Raymond Camden (<a href="https://codepen.io/cfjedimaster">@cfjedimaster</a>) <a href="https://codepen.io/cfjedimaster/pen/vWqNXZ/">表单校验 2</a></p>
155155
<script async src="https://production-assets.codepen.io/assets/embed/ei.js"></script>
156156

157-
## Another Example of Custom Validation
157+
## 另一个自定义校验的例子
158158

159-
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.
159+
在第三个示例中,我们已经构建了一些你可能在一些调研类应用中见过的东西。用户需要花掉“预算”来为歼星舰模型装配一套部件。总价必须等于 100。先看 HTML
160160

161161
``` html
162162
<form id="app" @submit="checkForm" action="https://vuejs.org/" method="post" novalidate="true">
@@ -193,7 +193,7 @@ For the third example, we've built something you've probably seen in survey apps
193193
</form>
194194
```
195195

196-
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.
196+
这组输入框覆盖了五个不同的部件。注意这里为 `v-model` 特性添加了 `.number`。它会告诉 Vue 将其值作为数字来使用。不过这里有一个小小的 bug,那就是当其值为空的时候,它会回到字符串格式,稍后你将会看到变通的办法。为了让用户使用起来更方便,我们添加展示了一个当前的总和,这样我们就能够实时的看到它们一共花掉了多少钱。现在我们来看看 JavaScript
197197

198198
``` js
199199
const app = new Vue({
@@ -208,7 +208,7 @@ const app = new Vue({
208208
},
209209
computed:{
210210
total:function() {
211-
//must parse cuz Vue turns empty value to string
211+
// 必须解析,因为 Vue 会将空值转换为字符串
212212
return Number(this.weapons)+
213213
Number(this.shields)+
214214
Number(this.coffee)+
@@ -226,21 +226,21 @@ const app = new Vue({
226226
})
227227
```
228228

229-
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:
229+
我们将总和设置为了一个计算属性,从那个我们解决掉的 bug 外面看上去,这已经足够了。我的 `checkForm` 方法现在只需要关注总和是不是 100 了。你可以在这里试用:
230230

231231
<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>
232232
<script async src="https://production-assets.codepen.io/assets/embed/ei.js"></script>
233233

234-
## Server-side Validation
234+
## 服务端校验
235235

236-
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:
236+
在我们最终的示例中,我们构建了一些用到 Ajax 的服务端校验的东西。这个表单将会问你为一个新产品起名字,并且将会确保这个名字是唯一的。我们快速写了一个 [OpenWhisk](http://openwhisk.apache.org/) serverless action 来进行这个校验。虽然这不是非常重要,但其逻辑如下:
237237

238238
``` js
239239
function main(args) {
240240

241241
return new Promise((resolve, reject) => {
242242

243-
// bad product names: vista,empire,mbp
243+
// 不好的产品名:vista, empire, mbp
244244
let badNames = ['vista','empire','mbp'];
245245
if(badNames.includes(args.name)) reject({error:'Existing product'});
246246
resolve({status:'ok'});
@@ -250,7 +250,7 @@ function main(args) {
250250
}
251251
```
252252

253-
Basically any name but "vista", "empire", and "mbp" are acceptable. Ok, so let's look at the form.
253+
基本上除了“vista”、“empire”和“mbp”的名字都是可以接受的。好,让我们来看看表单。
254254

255255
``` html
256256
<form id="app" @submit="checkForm" method="post">
@@ -274,7 +274,7 @@ Basically any name but "vista", "empire", and "mbp" are acceptable. Ok, so let's
274274
</form>
275275
```
276276

277-
There isn't anything special here. So let's go on to the JavaScript.
277+
这里没有任何特殊的东西。接下来我们再看看 JavaScript
278278

279279
``` js
280280
const apiUrl = 'https://openwhisk.ng.bluemix.net/api/v1/web/rcamden%40us.ibm.com_My%20Space/safeToDelete/productName.json?name=';
@@ -298,7 +298,7 @@ const app = new Vue({
298298
if(res.error) {
299299
this.errors.push(res.error);
300300
} else {
301-
// redirect to a new url, or do something on success
301+
// 在成功的时候重定向到一个新的 URL 或做一些别的事情
302302
alert('ok!');
303303
}
304304
});
@@ -308,15 +308,14 @@ const app = new Vue({
308308
})
309309
```
310310

311-
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:
311+
我们从一个运行在 OpenWhisk 的 API 的 URL 变量开始。现在注意 `checkForm`。在这个版本中,我们始终阻止了表单的提交 (当然,它也可以通过 Vue 在 HTML 中完成)。你可以看到一个基本的校验,即 `this.name` 是否为空,然后我们请求这个 API。如果名字是无效的,我们就添加一个错误。如果是有效的,我们就不做任何事 (只是一个 alert),但是你可以引导用户去一个新页面,在 URL 中带上产品的名字,或者其它行为。接下来你可以体验这个 demo
312312

313313
<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>
314314
<script async src="https://production-assets.codepen.io/assets/embed/ei.js"></script>
315315

316-
## Alternative Patterns
316+
## 其它替代模式
317317

318-
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:
318+
这份秘笈专注在“手动”校验表单,当然一些非常棒的 Vue 的库会为你搞定这些事情。使用一些预打包的库可能会影响你的应用最终的体积,但是好处是非常多的。这里有经过充分测试且保持日常更新的代码。其中包括以下 Vue 的表单校验库:
319319

320320
* [vuelidate](https://github.com/monterail/vuelidate)
321321
* [VeeValidate](http://vee-validate.logaretm.com/)
322-

0 commit comments

Comments
 (0)