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

How React-hook-form interacting with each another fields?

所以我基本上是新手 with-react-hook-form 我创建了一个带有受控输入的表单,其中我的第二次输入条件基于我的第一次输入。 我的第一个输入是持续时间,我有 2 个选项 'Monthly' 和 'Yearly'。 我的第二个输入是预算,其中每月的最低预算为 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。

非常感谢任何帮助。

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

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