昨天做了「分享經驗」的表單,可以輸入學校、系所、經歷與結果。但仔細想想,如果使用者亂填,資料格式就會變很亂,所以今天要來處理表單驗證,確保輸入格式正確。
HTML 本身也可以使用 input type 的方式指定格式 (像是底下例子),但是這不太靈活
<input type="text" required /> <!-- 必填 -->
<input type="number" min="0" max="100" /> <!-- 範圍 -->
<input type="url" /> <!-- URL 格式 -->
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>
自動顯示錯誤訊息