Search code examples
javascriptvue.jsvee-validate

How to prevent a custom field from validating on input with VeeValidate


I have a form that should validate only when clicking the "Submit" button. Every field works properly except for a custom field.

My form looks like this:

<template>
  <Form v-slot="{ validate }" :validation-schema="simpleSchema">
    First name:
    <div>
      <Field v-slot="{ field, meta }" name="firstName">
        <input v-bind="field" type="text" />
        {{ meta.validated }}
        {{ meta.valid }}
      </Field>
      <ErrorMessage name="firstName" />
    </div>
    Last name:
    <div>
      <Field v-slot="{ field, meta }" name="lastName">
        <input v-bind="field" type="text" />
        {{ meta.validated }}
        {{ meta.valid }}
      </Field>
      <ErrorMessage name="lastName" />
    </div>
    Item:
    <div>
      <InputText name="item" />
      <ErrorMessage name="item" />
    </div>

    <div>
      <button @click="validate">Submit</button>
    </div>
  </Form>
</template>

<script setup>
import { Form, Field, ErrorMessage, configure } from 'vee-validate';
import * as yup from 'yup';
import InputText from './InputText.vue';

configure({
  validateOnBlur: false,
  validateOnChange: false,
});

const simpleSchema = {
  firstName: yup.string().required(),
  lastName: yup.string().required(),
  item: yup.string().required(),
};
</script>

And custom field looks like this:

<template>
  <input v-model="value" type="text" />
  {{ meta.validated }}
  {{ meta.valid }}
</template>

<script setup>
import { useField } from 'vee-validate';

const props = defineProps({
  name: String,
});

const { value, meta } = useField(props.name);
</script>

Here is an example

As you'll see, when you fill the First name and Last name fields, meta.validated will only evaluate to true when you press "Submit", but if you do the same to the Item field, it evaluates to true as soon as you enter a value. How can I fix this so that the Item only evaluates when I press the "Submit" button?


Solution

  • Try passing this flag:

    const { value, meta } = useField(props.name, undefined, { validateOnValueUpdate: false });