vue3 + yup + vee-validate のフォームサンプル

npm i vee-validate@next --save
npm i yup

● vee-validate を使ってみる

<script lang="ts" setup>
import {Form, Field, ErrorMessage} from 'vee-validate'
import * as yup from 'yup'

interface FormValue {
  email: string
  password: string
  sortNo: number
}

const schema = yup.object({
  email: yup.string().required().email(),
  password: yup.string().required().min(8),
  sortNo: yup.number().required()
})

const handleSubmit = (value:FormValue) => {
  console.log( '● value' );
  console.log( value );
}
</script>

<template>
  <h1>Samplepageelement</h1>
  <Form @submit="handleSubmit" :validation-schema="schema">
    <div>
      <Field name="email" v-slot="{ value, field, errorMessage }">
        <el-form-item :error="errorMessage" label="Email">
          <el-input
              placeholder="メールアドレス xxx@yyy.zzz"
              v-bind="field"
              :validate-event="false"
              :model-value="value"
          />
        </el-form-item>
      </Field>

    </div>

    <div>
      <Field name="password" type="password"/>
      <ErrorMessage name="password" style="color: #c45656"/>
    </div>

    <div>
      <Field name="sortNo" type="number" />
      <ErrorMessage name="sortNo" style="color: #c45656"/>
    </div>

    <button>Submit</button>
  </Form>
</template>

結果

● value
{email: 'testuser@test.local', password: 'asdfasdfads', sortNo: '1'}

number型を期待しているsortNoがstringで返ってきてしまいます
明示的にcastするのが良いでしょうか。。。

https://bit.ly/3GlPvms

● vee-validate の useFormでリアクティブに値を取得する

<template>
  <div>
    <div>
      <Field name="age" as="input" type="number" />
      <div>{{ errors.age }}</div>
    </div>

    <div>
      <Field name="name" as="input" />
      <div>{{ errors.name }}</div>
    </div>

    <div>
      <Field name="password" as="input" type="password" />
      <div>{{ errors.password }}</div>
    </div>

    <pre>Is form dirty: {{ isDirty }}</pre>

    <!-- print form values -->
    <pre>{{ values }}</pre>
  </div>
</template>

<script lang="ts" setup>
import { defineComponent, computed } from 'vue'
import { Field, useForm } from 'vee-validate'
import * as yup from 'yup'

interface UserFormValues {
  age: number
  name: string
  password: string
}

const schema = yup.object().shape({
  age: yup.number().required(),
  name: yup.string().required(),
  password: yup.string().required().min(8)
})
const { meta, values, errors } = useForm<UserFormValues>({
  validationSchema: schema
})

const isDirty = computed(() => meta.value.dirty)
</script>
No.2239
11/29 15:01

edit