Yup React 中基于复选框值的验证

Validation in Yup React based on the value of checkbox

我正在使用 React-form-hook 在 React 中构建一个表单并使用 yup 进行验证。

我正在使用 watch() 检查复选框是否被点击,如果被点击,它将在表单中显示另一个输入字段,这在之前是不可见的。

即使我没有点击复选框,这意味着引用输入字段不可见或不呈现,它仍然不执行 handlesubmit。

我想不出解决这个问题的方法。

   <div className="form-check">
      <input type="checkbox" id="askRefer" {...register("askRefer")} />
      <label className="form-check-label" htmlFor="askRefer">
        Refered ?
      </label>
   </div>

  {referedStatus && (
      <div className="form-group">
        <label htmlFor="referedNumber">Refereed Number</label>
        <input
          type="text"
          className="form-control"
          placeholder="refer number"
          {...register("refer")}
        />
        {errors.refer && (
          <p className="error-message">{errors.refer.message}</p>
        )}
      </div>
    )}

验证码在yup.

const valSchema = yup.object().shape({
    email: yup.string()
          .required("email is required")
          .email("only accepts an email"),
    password: yup.string().required("password cannot be empty"),
    confirmPassword: yup.string()
           .required("confirmation of password is important")
           .oneOf([yup.ref("password"), null], "password doesn't match"),
    refer:yup.number()
             .required("please input refer number")
             .positive("entry should be greater than 0")
             .integer("input integer value"))
   });

再挂钩形式:

 const {register, handleSubmit, watch, formState: { errors }} = useForm({
                                                        resolver: yupResolver(valSchema),
                                                        mode: "onTouched",
                                                        });
let referedStatus= watch("askRefer", false);

如果有帮助,完整代码在这里:

import React from "react";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";

function Rform() {


  const valSchema = yup.object().shape({
    email: yup
      .string()
      .required("email is required")
      .email("only accepts an email"),
    password: yup.string().required("password cannot be empty"),
    confirmPassword: yup
      .string()
      .required("confirmation of password is important")
      .oneOf([yup.ref("password"), null], "password doesn't match"),
    refer:(yup
      .number()
      .required("please input refer number")
      .positive("entry should be greater than 0")
      .integer("input integer value"))
  });

  console.log(valSchema)

  const {
    register,
    handleSubmit,
    watch,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(valSchema),
    mode: "onTouched",
  });

let referedStatus= watch("askRefer", false);

  const onSubmit = (formData) => {
    let url = "http://localhost:4000/things/register";
    fetch(url, {
      method: "POST",
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify(formData)
    })
      .then((response) => response.json())
      .then((result) => console.log(result));
  };
  console.log(referedStatus);

  return (
    <div className="container" onSubmit={handleSubmit(onSubmit)}>
      <form>
        <div className="form-group">
          <label>Email address</label>
          <input
            className="form-control"
            aria-describedby="emailHelp"
            placeholder="Enter email"
            {...register("email")}
          />
          <small className="form-text text-muted">
                We don't share the credential.
          </small>
          {errors.email && (
            <p className="error-message">{errors.email.message}</p>
          )}
        </div>
        <div className="form-group">
          <label>Password</label>
          <input
            type="password"
            className="form-control"
            placeholder="Password"
            {...register("password")}
          />
          {errors.password && (
            <p className="error-message">{errors.password.message}</p>
          )}
        </div>

        <div className="form-group">
          <label>Password</label>
          <input
            type="password"
            className="form-control"
            placeholder="Password"
            {...register("confirmPassword")}
          />
          {errors.confirmPassword && (
            <p className="error-message">{errors.confirmPassword.message}</p>
          )}
        </div>

        <div className="form-check">
          <input type="checkbox" id="askRefer" {...register("askRefer")} />
          <label className="form-check-label" htmlFor="askRefer">
            Refered ?
          </label>
        </div>

        {referedStatus && (
          <div className="form-group">
            <label htmlFor="referedNumber">Refereed Number</label>
            <input
              type="text"
              className="form-control"
              placeholder="refer number"
              {...register("refer")}
            />
            {errors.refer && (
              <p className="error-message">{errors.refer.message}</p>
            )}
          </div>
        )}

        <button type="submit" className="btn btn-primary">
          Submit
        </button>
      </form>
    </div>
  );
}

export default Rform;

这是表单在浏览器中的样子。

这是因为在您的 yup 架构中需要可选字段“refer”(只要“askRefer”是 false)。您必须将“askRefer”复选框添加到 yup 模式,然后您可以通过 when 方法进行检查,如果“askRefer”为 true.

,则为“refer”设置验证
const valSchema = yup.object().shape({
  email: yup
    .string()
    .required("email is required")
    .email("only accepts an email"),
  password: yup.string().required("password cannot be empty"),
  confirmPassword: yup
    .string()
    .required("confirmation of password is important")
    .oneOf([yup.ref("password"), null], "password doesn't match"),
  askRefer: yup.boolean(),
  refer: yup.number().when("askRefer", {
    is: true,
    then: yup
      .number()
      .required("please input refer number")
      .positive("entry should be greater than 0")
      .integer("input integer value")
  })
});