npm install vee-validate --save
再於 main.js (Vue cli 中的 Vue 注入點),將這個套件匯入專案中:
@import VeeValidate* from 'vee-validate'
//因為是在node module 中的套件,所以只需要套件名稱就可以了
Vue.use(VeeValidate);
//名稱對應到上述 *,也就是我們為匯入的套件賦予的名稱
<input name="email">
<span v-if="errors.has('email')"></span>
這部分有點像是針對errors
給我們的更詳細的查閱。
vee-validate 透過 v-validate
和 name
做表單元素的分組和驗證;然後再由 error
這個物件告知使用者每一個綁定 v-validate 的 input 於驗證後產生的相關訊息。errors.has() 讓我們查閱 vee-validate 驗證後錯誤的 input 有哪些。例如, errors.has('email')
就是在查閱這個驗證錯誤的表單有沒有包含 email 這一項。
由這樣的使用方式可以得知,vee-validate 的 errors 運作方式有點像是 JS 的事件綁定。我們在事件綁定中,在 event handler 裡代入一個 e 或 event
的參數,就可以查閱這個事件被觸發時的各種相關訊息。
這邊也是相當類似的。透過 errors 這個物件,我們也可以查閱 vee-validate 在做過驗證之後,產生和驗證錯誤的表單的相關訊息。
而,errors.first('')
則是這個套件提供給我們使用的客戶端回饋訊息。(也就是在表單驗證錯誤時,給使用者看的訊息)
是給使用者的回饋訊息,以 Vue 的 {{ }}
方法顯示到網頁上。
<input name='email' v-validate="'required'">
<span v-if="error.has('email')">{{ errors.first('email') }}</span>
以 email 為例,使用first()
這個方法,vee-validate 就會針對 email 做驗證。除了一般的告知使用者 email 為必填,也可以回饋詳細的錯誤訊息,例如,email 的格式不對等等。
PS. 在 errors 中代入的參數都是 input 中 name 標籤裡的值,這部分要特別注意。
{{ }}
的方式渲染給使用者看在上述我們只是做好表單的驗證功能,但是並不會阻止瀏覽器送出表單。input 只認得 HTML 標籤的 required 屬性:
<input...required>
如果要做到 submit 之前,做好套件的驗證,再交由瀏覽器提出表單,就需要從 method 做處理,讓表單驗證成功之後,再向遠端資料庫送出表單內容。這時候就不需要使用 required 標籤,就可以讓顧客再填寫必須欄位後,再送出表單了。
this.$validator.validate().then(valid => {
// 提交表單的 ajax 行為
});
or
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up
Syntax | Example | Reference | |
---|---|---|---|
# Header | Header | 基本排版 | |
- Unordered List |
|
||
1. Ordered List |
|
||
- [ ] Todo List |
|
||
> Blockquote | Blockquote |
||
**Bold font** | Bold font | ||
*Italics font* | Italics font | ||
~~Strikethrough~~ | |||
19^th^ | 19th | ||
H~2~O | H2O | ||
++Inserted text++ | Inserted text | ||
==Marked text== | Marked text | ||
[link text](https:// "title") | Link | ||
 | Image | ||
`Code` | Code |
在筆記中貼入程式碼 | |
```javascript var i = 0; ``` |
|
||
:smile: | ![]() |
Emoji list | |
{%youtube youtube_id %} | Externals | ||
$L^aT_eX$ | LaTeX | ||
:::info This is a alert area. ::: |
This is a alert area. |
On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?
Please give us some advice and help us improve HackMD.
Do you want to remove this version name and description?
Syncing