vuelidate
でrequiredIf
(特定の条件のときだけ必須にする)に、reactiveな値を設定するのに結構苦戦したので、備忘録です。
(ドキュメントに書いてあったのでその通りにすればよかっただけ)
ゴールのイメージ
チェックボックス(リアクティブな値)がtrueの場合は、テキストボックスが必須になる。
falseの場合は、必須にならない。
検証環境
vue: 3.3.2
Composition API
@vuelidate/core:2.0.2
@vuelidate/validators": 2.0.2
ダメだった書き方
state.isChecked
がreactive
なのでこれで良いと思ったのですがダメでした。
<template> <div> <h1>Vuelidate</h1> <input type="checkbox" v-model="state.isChecked" @change="v$.mailAddress.$touch" /> <input type="text" v-model="state.mailAddress" @blur="v$.mailAddress.$touch" /> <div class="input-errors" v-for="error of v$.mailAddress.$errors" :key="error.$uid"> <div>{{ error.$message }}</div> </div> </div> </template> <script lang="ts"> import { computed, defineComponent, ref } from 'vue' import { reactive } from 'vue' import { useVuelidate } from '@vuelidate/core' import { required, requiredIf } from '@vuelidate/validators' export default defineComponent({ setup() { const state = reactive({ isChecked: false, mailAddress: '' }) const rules = { return { mailAddress: { required: requiredIf(() => state.isChecked)} } }) const v$ = useVuelidate(rules.value, state) return { state, v$ } } } </script>
正解
rules
をcomputed
にする!
あとはチェックボックスに @change="v$.mailAddress.$touch"
を設定するのもポイントでした。
const rules = computed(() => { return { mailAddress: { required: requiredIf(() => state.isChecked)} } })
ちゃんと公式に書いてあった
結論
公式ドキュメントをちゃんと読もう!