vue3でバリデーションについて調べたのでメモ
参考(https://www.npmjs.com/package/@vuelidate/core)
環境
vue3
typescript
vuelidateを使う
現時点でアルファ版ぽい
自分の環境ではバージョンの互換性がなかったので--legacy-peer-depsで強制的にインスコ
npm install @vuelidate/core @vuelidate/validators --save --legacy-peer-deps
main.ts
import { createApp } from 'vue'
import App from './App.vue'
import { VuelidatePlugin } from '@vuelidate/core'
const app = createApp(App)
app.use(VuelidatePlugin)
app.mount('#app')
App.vue
<template>
<div>
<input v-model="emailAddress" label="メールアドレス" @blur="$v.emailAddress.$touch()" >
<p v-for="(error, index) of $v.$errors" :key="index">
{{ error }}
</p>
</div>
</template>
<script lang="ts">
import { ref } from 'vue'
import { useVuelidate } from '@vuelidate/core'
import { email, required } from '@vuelidate/validators'
export default {
setup () {
const name = ref('')
const emailAddress = ref('')
const rules = {
name: { required },
emailAddress: { required, email }
}
const $v = useVuelidate(rules, { name, emailAddress })
return { name, emailAddress, $v }
}
}
</script>
こんな感じです