是的密码确认验证不起作用

Yup password confirmation validation doesn't work

我想用 Yup 验证密码确认,但它不起作用。

这是我的代码:

<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>

这是demo code on codesandbox

当运行上面的代码没有出现错误但密码确认不起作用。

任何人都可以帮助密码确认工作吗?

显然唯一有效的方法是在 useForm

中使用 validationSchema

最终的设置函数如下所示:

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,
    };
},