Validate on blur using vee-validate 4 composition api

127 Views Asked by At

I'm using Vue 3, composition api, with Vee-Validate 4, also composition api. I want my input fields to be validated on blur, but I can't seem to figure out how to do that. Currently the input fields are validated on input. The documentation states that "You are responsible for when the field validates, blurs or when its value changes." and also talks about handleBlur: https://vee-validate.logaretm.com/v4/api/use-field/ ..but how?

My code looks like this:

<template>
    <form @submit="onSubmit">
        <CustomInput
            v-model="phone"
            :invalid="!!phoneError"
            :errorMessage="phoneError"/>
        <button type="submit">Save</button>
    </form>
</template>

<script setup lang="ts">
import { useField, useForm } from "vee-validate";
import { store } from "@/store";
import { computed } from "vue";

const customer = computed(() => store.getters.getCustomer);

const formValues = {
  phone: customer.value?.phone,
};

const { handleSubmit } = useForm({
  initialValues: formValues,
});

const { value: phone, errorMessage: phoneError } = useField<string>('phone', 'requiredPhone');

const onSubmit = handleSubmit(() => {
  // do stuff
});

</script>

Where requiredPhone is a custom validation rule I've created. I created a small component using Vee-Validate components instead and it works fine with validating on blur, but it would be great if I could solve how to do it with composition api so I don't have to rewrite a whole bunch of code. It has to be possible, right? I'm using vee-validate 4.5.8, so it's not the most recent version. I don't know if that would have an impact?

Anyone who has any idea that might help me out?

0

There are 0 best solutions below