React-hook-form 如何与其他字段交互?

问题描述 投票:0回答:2

所以我基本上是新的 with-react-hook-form 我创建了一个带有受控输入的表单,其中第二个输入的条件基于我的第一个输入。 我的第一个输入是持续时间,我有两个选项“每月”和“每年”。 我的第二个输入是预算,其中每月的最低预算为 200,每年的最低预算为 400。

这是我的代码:

<div style={{ marginTop: theme.spacing(1) }}>
    <Controller
      as={Select}
      row
      name="duration"
      control={control}
      defaultValue="Monthly"
      fullWidth
      label={<FormattedMessage {...messages.duration} />}
      margin="normal"
      options={DURATION_OPTIONS}
      rules={{
        required: 'Required'
      }}
    />
  </div>


  <div>
    <Controller
      as={NumberField}
      row
      name="budget"
      control={control}
      defaultValue="1000"
      fullWidth
      label={<FormattedMessage {...messages.howMuchBudget} />}
      margin="normal"
      rules={{
        required: true,
        min: {
          value: 400,
          message: 'Min is 400',
        }
      }}
    />
  </div>

现在我想根据我的第一个字段验证动态触发我的第二个字段验证。如果我选择的持续时间为每月,则第二个输入的最小验证应为 200,如果我的持续时间选择为每年,则第二个输入的最小验证应为 400。

任何帮助将不胜感激。

reactjs react-hooks react-hook-form
2个回答
9
投票

这是一个基本示例。在这种情况下,姓氏必须比名字短,否则会出现错误。

function App() {
  const { register, handleSubmit, errors, getValues } = useForm({mode:'onChange'});

  const onSubmit = (data) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label>First name</label>
      <input name="firstName" defaultValue='Potato' ref={register} />

      <label>Last name (must be shorter than first name)</label>
      <input name="lastName" ref={register({
        validate: {
          shorterThanFirstName: value => value.length < getValues().firstName?.length,
        }
      })} />
      {errors.lastName && <p>Last name must be shorter than first name</p>}

      <input type="submit" />
    </form>
  );
}

0
投票

使用 yup 验证的示例:

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

const MY_SENSORED_CONST = "4";

const schema = yup
.object({
    fieldStringArray: yup.string().nullable(),
    fieldDependsOnAnother: yup
    .string()
    .when("fieldStringArray", (fieldAreaOfUse, schema) => {
        const currStrArr = fieldAreaOfUse[0]; // probably only array when using radiobuttons
        if (currStrArr.split(",").includes(MY_SENSORED_CONST)) {
            return schema.required();
        }
        return schema.nullable();
    }),
})
.required();

export function Component(props: any /*not any but u dont need to know*/) {

    const {
        register,
        handleSubmit,
        formState: { errors },
    } = useForm({
        resolver: yupResolver(schema),
        mode: "onChange",
        reValidateMode: "onChange",
    });
    const onSubmit = (/* data */) => props.next(); // this is only called when all fields were valid
    
    return (
        <form onSubmit={handleSubmit(onSubmit)}>
            <input
                {...register("fieldStringArray")}
            />
            <input
                {...register("fieldDependsOnAnother")}
            />

            <button type="submit">Send it</button>
        </form>
    );
}
© www.soinside.com 2019 - 2024. All rights reserved.