logaretm / vee-validate

✅ Painless Vue forms
https://vee-validate.logaretm.com/v4
MIT License
10.85k stars 1.28k forks source link

Vee-Validation v4 serverside error message on ErrorMessage tag #4334

Closed MicroDreamIT closed 1 year ago

MicroDreamIT commented 1 year ago

I am trying to develop a pretty big form, I using Nuxt3 and Vee-validation version 4. I am trying to get error from the server but for the limitation of documentation without example and resources in the internet I am having trouble to solve this problem.

<Form @submit="onSubmit" :validation-schema="schema" v-slot="{ errors }">
      <div>
           <label class="input-label" for="first_name">First Name</label>
           <input name="first_name" class="input-text" type="text" id="first_name" v-model="form.first_name">
           <ErrorMessage class="text-red-500" name="first_name" />
      </div>
      <div>
           <label class="input-label" for="email">Email</label>
           <input name="email" class="input-text" type="text" id="email" v-model="form.email">
           <ErrorMessage class="text-red-500" name="email" />
      </div>
</Form>
<script lang="ts" setup>
import { Form, Field, ErrorMessage, useForm } from 'vee-validate';

const schema = {
    first_name: 'required'
    email: 'required'
}
const form = ref<Object>({
    first_name:'',
    email: ''
})
const onSubmit = async () => {
    const { data, error } = await useFetch('http://localhost:8000/api/accounts/register', {
        method: 'post',
        body: form
    })
    console.log(error.value.data);
}

And here is my server response is look like on console

{"email":["This field may not be blank."]}

Now how am I supposed to display this on the field of email ErrorMessage tag? and how am I supposed to look at errorsBag?

logaretm commented 1 year ago

The ErrorMessage component is only used for display. You can set initial-errors on the form as documented here.

You can set them with onMounted or pass the prop directly and it should work. Let me know if that doesn't work for you.

If you are not looking for initial errors then you can use the $ref API to set errors dynamically, or use the composition which makes this even easier.