Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
VeeValidateによるフォームバリデーションの実装
Search
YRyu
May 15, 2024
Programming
0
190
VeeValidateによるフォームバリデーションの実装
NuxtプロジェクトにVeeValidateを導入し、フォームバリデーションを実装する手順を紹介します。
YRyu
May 15, 2024
Tweet
Share
Other Decks in Programming
See All in Programming
疑似コードによるプロンプト記述、どのくらい正確に実行される?
kokuyouwind
0
130
PostgreSQLで手軽にDuckDBを使う!DuckDB&pg_duckdb入門/osc25hi-duckdb
takahashiikki
0
240
これならできる!個人開発のすゝめ
tinykitten
PRO
0
150
大規模Cloud Native環境におけるFalcoの運用
owlinux1000
0
250
例外処理とどう使い分ける?Result型を使ったエラー設計 #burikaigi
kajitack
16
4.9k
CSC307 Lecture 04
javiergs
PRO
0
620
Vibe codingでおすすめの言語と開発手法
uyuki234
0
160
AtCoder Conference 2025
shindannin
0
920
Cap'n Webについて
yusukebe
0
160
AIで開発はどれくらい加速したのか?AIエージェントによるコード生成を、現場の評価と研究開発の評価の両面からdeep diveしてみる
daisuketakeda
1
580
コマンドとリード間の連携に対する脅威分析フレームワーク
pandayumi
1
140
re:Invent 2025 トレンドからみる製品開発への AI Agent 活用
yoskoh
0
600
Featured
See All Featured
Highjacked: Video Game Concept Design
rkendrick25
PRO
1
260
YesSQL, Process and Tooling at Scale
rocio
174
15k
The Cost Of JavaScript in 2023
addyosmani
55
9.4k
Scaling GitHub
holman
464
140k
Raft: Consensus for Rubyists
vanstee
141
7.3k
Neural Spatial Audio Processing for Sound Field Analysis and Control
skoyamalab
0
140
Fight the Zombie Pattern Library - RWD Summit 2016
marcelosomers
234
17k
Winning Ecommerce Organic Search in an AI Era - #searchnstuff2025
aleyda
0
1.8k
Are puppies a ranking factor?
jonoalderson
0
2.6k
Keith and Marios Guide to Fast Websites
keithpitt
413
23k
Typedesign – Prime Four
hannesfritz
42
2.9k
Google's AI Overviews - The New Search
badams
0
890
Transcript
VeeValidateによる フォームバリデーションの実装 @YRyu
⽬次 1. はじめに 2. 開発環境 3. フォーム作成 4. VeeValidate導⼊ 5.
バリデーション実装 6. 送信時のボタン制御 7. エラー箇所へスクロール 8. おわりに 2
はじめに VeeValidateとは... フォーム実装に必要な機能を兼ね備えたVue向けのモジュール - Form state and value tracking -
UX - Synchronous and Asynchronous Validation - Handling submissions 3
開発環境 node : 18.18.2 npm : 8.19.3 nuxt : 3.11.2
vee-validate : 4.12.6 yup : 1.4.0 ✓ VeeValidateはv3からv4へのメジャーアップデートで⼤きく仕様が変更されました ✓ Yupはバリデーションスキーマを定義するJSモジュールです 4
フォーム作成 Nuxtを⽤いてプロジェクトを作成し、基本的なログイン機能の実装を⾏う 5 interface LoginBody { email: string password: string
} export default defineEventHandler(async (event) => { const body = await readBody<LoginBody>(event) if (body.email === '
[email protected]
' && body.password === 'password') { return '認証に成功しました。 ' } else { throw createError('認証に失敗しました。 ') } }) /server/api/login.post.ts
Nuxtを⽤いてプロジェクトを作成し、基本的なログイン機能の実装を⾏う フォーム作成 <template> <h1>ログインページ </h1> <form @submit.prevent="submit()"> <input v-model="formData.email" type="email"
name="email" placeholder="メールアドレス " /> <input v-model="formData.password" type="password" name="password" placeholder="パスワード" /> <button>ログイン</button> <span v-if="errorMessage">{{ errorMessage }}</span> </form> </template> 6 /pages/login.vue <script setup lang="ts"> const formData = ref({ email: '', password: '' }) const errorMessage = ref('') const submit = async () => { const { error } = await useFetch('/api/login', { method: 'POST', body: formData.value }) if (error.value) { errorMessage.value = error.value.data.message || '予期せぬエラーが発生しました。 ' } else { errorMessage.value = '' navigateTo('/') } } </script>
1. VeeValidateとYupのインストールを⾏う > npm i vee-validate yup VeeValidate導⼊ 7
2. VeeValidateのComposition APIを使って、作成したフォームを書き換える VeeValidate導⼊ 8 + const submit = handleSubmit(
+ async (values) => { + const { error } = await useFetch('/api/login', { + method: 'POST', + body: values + }) + if (error.value) { + errorMessage.value = error.value.data.message + || '予期せぬエラーが発生しました。 ' + } else { + errorMessage.value = '' + navigateTo('/') + } + } + ) </script> /pages/login.vue <script setup lang="ts"> + import { useForm, useField } from 'vee-validate' - const formData = ref({ email: '', password: '' }) + const { handleSubmit } = useForm() + const { value: email } = useField('email') + const { value: password } = useField('password') const errorMessage = ref('') - const submit = async () => { - const { error } = await useFetch('/api/login', { - method: 'POST', - body: formData.value - }) - if (error.value) { - errorMessage.value = error.value.data.message - || '予期せぬエラーが発生しました。 ' - } else { - errorMessage.value = '' - navigateTo('/') - } - }
2. VeeValidateのComposition APIを使って、作成したフォームを書き換える VeeValidate導⼊ <template> <h1>ログインページ </h1> <form @submit.prevent="submit()"> -
<input v-model="formData.email" type="email" name="email" placeholder="メールアドレス " /> + <input v-model="email" type="email" name="email" placeholder="メールアドレス " /> - <input v-model="formData.password" type="password" name="password" placeholder="パスワード" /> + <input v-model="password" type="password" name="password" placeholder="パスワード" /> <button>ログイン</button> <span v-if="errorMessage">{{ errorMessage }}</span> </form> </template> 9 /pages/login.vue
バリデーション実装 Yupのバリデーションスキーマを使って、フォームにバリデーションを追加する 10 <script setup lang="ts"> import { useForm, useField
} from 'vee-validate' + import { string } from 'yup' - const { handleSubmit } = useForm() + const { handleSubmit } = useForm({ + validationSchema: { + email: string().email().required(), + password: string().min(8).max(16).required() + } + }) - const { value: email } = useField('email') + const { value: email, errorMessage: emailError } = useField('email') - const { value: password } = useField('password') + const { value: password, errorMessage: passwordError } = useField('password') const errorMessage = ref('') const submit = handleSubmit( async (values) => { const { error } = await useFetch('/api/login', { method: 'POST', body: values }) if (error.value) { errorMessage.value = error.value.data.message || '予期せぬエラーが発生しました。 ' } else { errorMessage.value = '' navigateTo('/') } - } + }, + () => { + errorMessage.value = '入力内容に誤りがあります。 ' + } ) </script> /pages/login.vue
バリデーション実装 Yupのバリデーションスキーマを使って、フォームにバリデーションを追加する 11 <template> <h1>ログインページ </h1> <form @submit.prevent="submit()"> <input v-model="email"
type="email" name="email" placeholder="メールアドレス " /> + <span v-if="emailError">{{ emailError }}</span> <input v-model="password" type="password" name="password" placeholder="パスワード" /> + <span v-if="passwordError">{{ passwordError }}</span> <button>ログイン</button> <span v-if="errorMessage">{{ errorMessage }}</span> </form> </template> /pages/login.vue
フォーム送信時にボタンの制御を⾏う 送信時のボタン制御 12 <script setup lang="ts"> import { useForm, useField
} from 'vee-validate' import { string } from 'yup' - const { handleSubmit } = useForm({ + const { handleSubmit, isSubmitting } = useForm({ validationSchema: { email: string().email().required(), password: string().min(8).max(16).required() } }) const { value: email, errorMessage: emailError } = useField('email') const { value: password, errorMessage: passwordError } = useField('password') const errorMessage = ref('') const submit = handleSubmit( /* 省略 */ ) </script> <template> <h1>ログインページ </h1> <form @submit.prevent="submit()"> <input v-model="email" type="email" name="email" placeholder="メールアドレス " /> <span v-if="emailError">{{ emailError }}</span> <input v-model="password" type="password" name="password" placeholder="パスワード" /> <span v-if="passwordError">{{ passwordError }}</span> - <button>ログイン</button> + <button :disabled="isSubmitting"> + {{ isSubmitting ? 'ログイン中...' : 'ログイン' }} + </button> <span v-if="errorMessage">{{ errorMessage }}</span> </form> </template> /pages/login.vue
エラー箇所へスクロール 検知したバリデーションエラーの発⽣箇所へスクロールさせる 13 <script setup lang="ts"> import { useForm, useField
} from 'vee-validate' import { string } from 'yup' const { handleSubmit, isSubmitting } = useForm({ validationSchema: { email: string().email().required(), password: string().min(8).max(16).required() } }) const { value: email, errorMessage: emailError } = useField('email') const { value: password, errorMessage: passwordError } = useField('password') const errorMessage = ref('') const submit = handleSubmit( async (values) => { /* 省略 */ }, - () => { + ({ errors }) => { errorMessage.value = '入力内容に誤りがあります。 ' + document.querySelector( + `input[name="${Object.keys(errors)[0]}"]` + )?.scrollIntoView({ + behavior: 'smooth' + }) } ) </script> /pages/login.vue
おわりに VeeValidateを⽤いることで、以下の機能を簡単に実装することができた - バリデーションの実装 - エラーメッセージの表⽰ - 送信ボタンの制御 - エラー箇所へのスクロール
また、Composition APIを使った実装により、カスタムコンポーネントへの拡張 性も⾮常に⾼いと感じた 14
参考 [1] https://nuxt.com/docs/getting-started/introduction [2] https://vee-validate.logaretm.com/v4/guide/overview/ [3] https://github.com/jquense/yup 15