I want to validate password confirmation with Yup but it doesn't work.
This is my code :
<template>
<form @submit="onSubmit">
<div>
<label for="password">Password</label>
<div>
<input
id="password"
v-model.trim="password"
name="password"
/>
</div>
</div>
<div>{{ passwordErrorMessage }}</div>
<br>
<div>
<label for="confirmPassword">Confirm Password</label>
<div>
<input
id="confirmPassword"
v-model.trim="confirmPassword"
name="confirmPassword"
/>
</div>
</div>
<div>{{ confirmPasswordErrorMessage }}</div>
<br>
<button>Submit</button>
</form>
</template>
<script>
import { useField, useForm } from "vee-validate";
import * as yup from "yup";
export default {
setup() {
const { handleSubmit } = useForm();
const onSubmit = handleSubmit((values) => {
alert(JSON.stringify(values, null, 2));
});
const { value: password, errorMessage: passwordErrorMessage } = useField(
"password",
yup
.string()
.required()
.min(5)
);
const { value: confirmPassword, errorMessage: confirmPasswordErrorMessage } = useField(
"confirmPassword",
yup
.string()
.required()
.oneOf([yup.ref("password")], "Passwords do not match"),
);
return {
password,
passwordErrorMessage,
confirmPassword,
confirmPasswordErrorMessage,
onSubmit
}
}
};
</script>
This is the demo code on codesandbox
When running the code above no error appears but the password confirmation does not work.
Can anyone help just to get the password confirmation to work?
CodePudding user response:
Apparently the only way it works is by using validationSchema in the useForm
The final setup function will look like this:
setup() {
const {
handleSubmit
} = useForm({
validationSchema: yup.object({
password: yup.string().required().min(5),
confirmPassword: yup
.string()
.required()
.oneOf([yup.ref("password")], "Passwords do not match"),
}),
});
const onSubmit = handleSubmit((values) => {
alert(JSON.stringify(values, null, 2));
});
const {
value: password,
errorMessage: passwordErrorMessage
} = useField(
"password"
);
const {
value: confirmPassword,
errorMessage: confirmPasswordErrorMessage,
} = useField("confirmPassword");
return {
password,
passwordErrorMessage,
confirmPassword,
confirmPasswordErrorMessage,
onSubmit,
};
},