A Donglaotian
A Donglaotian

Reputation: 1

vee-validate & yup: how to display multiple validation errors and not just single error message (fast-exist)

Hey I just starting learning vue 3, vee-validate and yup and I want to display multiple validation errors below input and not just single error message, like this

detail-expected

I tried to use defineField from vee-validate useForm but the docs is not mentioning anything about this usecase

Upvotes: 0

Views: 180

Answers (1)

A Donglaotian
A Donglaotian

Reputation: 1

Nevermind I read again vee-validate docs and found out a way to display multiple errors messages, in case you right wondering, here is my code with vue 3 SFC typescript

<template>
    <div>
        <form @submit.prevent="onSubmit">
            <input type="password" v-model="newPassword" v-bind="newPasswordAttrs" placeholder="password" /><br>
            <small class="error" v-for="error in newPasswordAttrs.errors">
                {{ error }}<br>
            </small> <br>
            <input type="password" v-model="confirmPassword" v-bind="confirmPasswordAttrs" placeholder="confirm password" /><br>
            <small class="error" v-for="error in confirmPasswordAttrs.errors">
                {{ error }}<br>
            </small> <br>
            <button type="submit">Submit</button>
        </form>
    </div>
</template>

<script setup lang="ts">
import { toTypedSchema } from '@vee-validate/yup';
import { useForm } from 'vee-validate';
import * as yup from 'yup';

const oldPassword = '12345678';

const { handleSubmit, defineField } = useForm({
    validationSchema: toTypedSchema(
        yup.object({
            newPassword: yup
                .string()
                .required()
                .min(8)
                .max(16)
                .default('')
                .test('password', 'Password must be different from the old password', (value) => value !== oldPassword),
            confirmPassword: yup
                .string()
                .required()
                .oneOf([yup.ref('newPassword')], 'Passwords must match')
                .default('')

        })
    )
});

const onSubmit = handleSubmit((values) => {
    // do something with the values
    alert(`values: ${JSON.stringify(values)}`);
});

const [newPassword, newPasswordAttrs] = defineField(
    'newPassword',
    {
        props: (state) => ({
            errors: state.errors // here is how I do it
        })
    }
);
const [confirmPassword, confirmPasswordAttrs] = defineField(
    'confirmPassword',
    {
        props: (state) => ({
            errors: state.errors // here is how I do it
        })
    }
);

</script>

<style scoped>
.error {
    color: red;
}
</style>

Upvotes: 0

Related Questions