LoginSignup
7
2

More than 1 year has passed since last update.

【Composition API】フォームにバリデーションをつける方法 【Script SetUp】

Last updated at Posted at 2022-10-28

始めに

以下のコードはこちらで利用しているものです。
良ければご覧ください。
見なくても理解いただく上では問題ありません。

開発環境

MacBook Air (M1, 2020)
npm 8.18.0

バリデーション

以下の二つの処理を実行させるコードを書きます。

  • 複数のフォームにバリデーションをつける
  • クリアしないとボタンをクリックできなくする。

ではご覧ください。

<script setup lang="ts">
import { useStore } from '../../store'
import { useField, useForm } from 'vee-validate';
//yupを利用することでエラーメッセージを表示させる関数を書かずにバリデーションができる。
import { object, string } from 'yup';
    //スキーマでバリデーションを一括管理する。
    const schema = object({
        list_description: string().required('必須の項目です。').label('リスト名'),
    });

    //useFormを使用することでバリデーションの処理をまとめることができる。
//metaを使用し、initialValuesを設定することで、どちらのバリデーションもパスしないとバリデーションがクリアできなくする。
    const { errors, meta } = useForm({
        //作成したスキーマを設定
        validationSchema: schema,
        initialValues: {
            list_description: '',
        },
    });
    
    //valueを取り出す。
    const { value: list_description } = useField<string>('list_description');

    const clearForm = () => {
        list_description.value = ""
    };

    const store = useStore()

    const addList = () =>{
        store.dispatch('todoLists/addList', {
            id: Math.floor(Math.random() * 100000),
            description: list_description.value,
            todoCards: []
        });
        clearForm();
    }
</script>

<template>
  <div>
    <form @submit.prevent="addList">
        <span v-if="errors.list_description">
            <!--エラーがあればエラー文を表示-->
            {{ errors.list_description }}
        </span><br>
        <input type="text" id="description" v-model="list_description" /><br>
        <!--:disabled=!meta.validを設定することで、どちらのバリデーションもクリアしないとボタンをクリックできなくする。-->
        <input type="submit" value="submit" :disabled="!meta.valid" />
    </form>
  </div>
  <hr />
</template>

7
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
2