How to make conditional validate with Yup with computed value in conditional?
There is variable const isVerifiedPhone = computed<boolean>(() => !!authStore.profile?.phone);
There is validation
const { values, errors, submit } = useForm(
yup.object({
phone: yup
.string()
.default('')
.required('Введите номер телефона')
.length(10, 'Номер телефона должен включать 10 цифр'),
email: isVerifiedPhone.value
? yup.string().email('Введите Email').default('').required('Введите имя')
: yup.string().email('Введите Email').default(''),
}),
{
defaultValues: {
phone: userPhone.value,
email: userEmail.value,
},
},
);
With this structure condition isVerifiedPhone.value doesnt update inside useForm
I tried that way
email: yup.string().email('Введите Email').default('').when(isVerifiedPhone.value, {
is: true,
then: yup.string().email('Введите Email').default('').required('Введите имя'),
otherwise: yup.string().email('Введите Email').default('')
})
But I have error into property is
And I tried that way
email: yup.string().email('Введите Email').default('').when([], {
is: () => isVerifiedPhone.value,
then: yup.string().email('Введите Email').default('').required('Введите имя'),
otherwise: yup.string().email('Введите Email').default('')
})
and also have a error into property is
How I can do this? I need that my email field will required if only isVerifiedPhone.value === true I found only ways conditional validate with fileds inside form, but this is not I need
To achieve conditional validation with a computed value in Vue 3 with TypeScript using Yup, you can use a slightly different approach. Instead of using the .when() method directly with the computed property, you can create a custom validation function that checks the value of isVerifiedPhone and returns the appropriate schema.
Here's how you can do it:
the emailValidation function returns the appropriate Yup schema based on the value of isVerifiedPhone. This way, the validation schema for the email field is dynamically determined by the computed property.