如何使用 React Hook Form 验证自动完成多个 TextField 是的?

Val*_*ler 3 reactjs material-ui yup react-hook-form

我正在使用 Material UI 的自动完成多个 TextField、React Hook Form 和 Yup 来验证表单输入。

当我对 daysOfWeek 使用 Yup.string() 时,即使我选择了值,它也会显示错误消息。但是,如果我将其更改为 Yup.array(),则会显示以下错误...

daysOfWeek 必须是一个array类型,但最终值是:(null 从 value 转换"")。如果“null”旨在作为空值,请务必将架构标记为.nullable()

有没有办法使用 Yup 来验证 Material UI 的自动完成多个 TextField?先感谢您!

这是我的相关代码...

    const [selected, setSelected] = useState([]);

    const validationSchema = Yup.object().shape({
        daysOfWeek: Yup.string()
            .required("Days of the week are required")
    });

    const {
        formState: {errors},
        handleSubmit,
        register
    } = useForm({
        resolver: yupResolver(validationSchema)
    });

   <Autocomplete
       disableClearable
       disablePortal
       filterSelectedOptions
       multiple
       getOptionDisabled={(option) => option.disabled ? true : false}
       getOptionLabel={(option) => option.label}
       id="days-autocomplete"
       onChange={(event, value) => onOptionsChange(event, value)}
       options={daysOfWeekSuggestions}
       renderInput={(params) => <TextField
           required
           error={errors.daysOfWeek ? true : false}
           id="daysOfWeek"
           label="Days of the week"
           name="daysOfWeek"
           type="search"
           {...params}
           {...register("daysOfWeek")}
       />}
       value={selected}
   />

   <Typography color="error" sx={errorSx} variant="inherit">{errors.daysOfWeek?.message}</Typography>
Run Code Online (Sandbox Code Playgroud)

kno*_*fel 6

我制作了一个小型沙盒并更改了一些内容以使其正常工作:

  • 你应该使用<Controller />而不是register像MUI这样的外部控制组件<Autocomplete />
  • 因为你必须传递一个defaultValuefor <Controller/>(在你的情况下是一个空数组) - 然后你可以使用Yup.min数组的方法来测试用户是否至少选择了一周中的一天并摆脱测试,Yup.required因为他们都做了更多或你的情况不太一样
  • 您可以使用helperText属性<Autocomplete />来显示错误消息
  • 您可以将reffrom传递<Controller />inputRefof 的属性<TextField />,这样当您提交而不选择一周中的某一天时,它会自动为用户聚焦该字段
const validationSchema = Yup.object().shape({
  daysOfWeek: Yup.array()
    .of(
      Yup.object().shape({
        value: Yup.string(),
        label: Yup.string()
      })
    )
    .min(1, "Days of the week are required")
});
Run Code Online (Sandbox Code Playgroud)
<Controller
  name="daysOfWeek"
  control={control}
  defaultValue={[]}
  render={({ field: { ref, ...field }, fieldState: { error } }) => (
    <Autocomplete
      {...field}
      disableClearable
      disablePortal
      filterSelectedOptions
      multiple
      getOptionDisabled={(option) => option.disabled}
      getOptionLabel={(option) => option.label}
      id="days-autocomplete"
      onChange={(event, value) => field.onChange(value)}
      options={daysOfWeekSuggestions}
      renderInput={(params) => (
        <TextField
          required
          error={!!error}
          helperText={error?.message}
          id="daysOfWeek"
          label="Days of the week"
          name="daysOfWeek"
          type="search"
          inputRef={ref}
          {...params}
        />
      )}
    />
  )}
/>
Run Code Online (Sandbox Code Playgroud)

编辑组合框材质演示(分叉)