Search code examples
javascriptvue.jsvuejs3vee-validate

[email protected] - how to manually validate field


While using

I encountered following problem:

<Form @submit="onSubmit" :validation-schema="schema">
  <div class="mb-3">
    <label for="edit-email" class="form-label">E-mail</label>
    <Field
      id="edit-email"
      class="form-control"
      name="email"
      type="text"
      :validateOnInput="true"
    />
    <ErrorMessage class="invalid-feedback" name="email" />
  </div>

  <button @click="checkEmail" type="button">Check e-mail address</button>


  <!-- non-important part of the form -->
</Form>

I'd like to manually validate <Field /> when the button is clicked (error message should appear) and then I want to use the field's value to perform another action.

I wrote following code:

import { useFieldValue } from 'vee-validate';

// setup
setup() {  
    const schema = object({ 
      email: string().required().email().label("e-mail"), 
    });
 
    function verifyEmail(v) {
      const emailValue = useFieldValue("email");
      console.log(emailValue); // empty ComputedRefImpl
    }

    return { 
      schema, 
      verifyEmail,
    };
  },
}

And this doesn't work. emailValue is returned as ComputedRefImpl with an undefined value.

I guess I'm mixing Components & Composition API flavors of vee-validate. But still don't know how to resolve this issue.

Created sandbox with this: https://codesandbox.io/s/vue3-vee-validate-form-field-forked-xqtdg?file=/src/App.vue

Any help will be much appreciated!


Solution

  • According to vee-validate's author: https://github.com/logaretm/vee-validate/issues/3371#issuecomment-872969383

    the useFieldValue only works as a child of a useForm or useField.

    So it doesn't work when <Field /> component is used.