iT邦幫忙

2025 iThome 鐵人賽

DAY 9
0
Vue.js

Vue 新手學習紀錄系列 第 9

Day 9|用 vee-validate 做表單驗證

  • 分享至 

  • xImage
  •  

昨天做了「分享經驗」的表單,可以輸入學校、系所、經歷與結果。但仔細想想,如果使用者亂填,資料格式就會變很亂,所以今天要來處理表單驗證,確保輸入格式正確。

為什麼要做表單驗證?

  • 避免髒資料:例如有人輸入「AAA」當年度。
  • 提升使用者體驗:即時的錯誤提示,而不是按下送出後才跳 alert。
  • 資料一致性:後端收到的資料格式會更一致,也會更符合我們想要的內容,後續處理也方便。

HTML 本身的驗證

HTML 本身也可以使用 input type 的方式指定格式 (像是底下例子),但是這不太靈活

<input type="text" required /> <!-- 必填 -->
<input type="number" min="0" max="100" /> <!-- 範圍 -->
<input type="url" /> <!-- URL 格式 -->

為什麼要用 vee-validate?

  • 內建 Field / ErrorMessage 元件: 欄位與錯誤訊息自動綁定
  • 支援 Yup Schema: 規則集中管理、易擴充
  • 即時驗證: 使用者打字就能看到錯誤訊息,不用等到送出才知道

Yup 是什麼?

Yup 是一個 JavaScript 的物件驗證函式庫,它能夠幫我們定義一份「規則(schema)」來驗證資料是否正確。

實作步驟

安裝套件

npm install vee-validate yup

定義規則
在 src 中新增 validation 的資料夾,並新增 postSchema.js 檔案,在這個檔案中放入表單各欄位的規則

import * as Yup from 'yup'

const postSchema = Yup.object({
  pSchool: Yup.string().required('學校必填'),
  pDep: Yup.string().required('系所必填'),
  pYear: Yup.number()
    .typeError('年度必須是數字')
    .required('推甄年度必填'),
  pURL: Yup.string().url('URL 格式錯誤').nullable(),
})


export default postSchema;

修改昨天的表單
將表單換成 <Form><ErrorMessage><Field>,並綁定上面所定的規則

 <Form :validation-schema="postSchema" @submit="submitExperience" class="share-form">
      <div class="form-section">
        <h4 class="section-title">📚 基本資訊</h4>
        <div class="form-grid">
          <div class="form-group">
            <label class="form-label">學校</label>
            <Field name="pSchool" type="text" class="form-input" placeholder="例:台灣大學" />
            <ErrorMessage name="pSchool" class="error" />
          </div>
          ...
 </Form>

如果沒有按照規則填寫,就可以看到相對應的錯誤提示

小結

  • 用 Yup 定義集中式規則
  • <Field> 綁定輸入欄位
  • <ErrorMessage> 自動顯示錯誤訊息

上一篇
Day 8|實作新增資料
系列文
Vue 新手學習紀錄9
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言