如何在反应中使用表单挂钩验证反应-select 下拉列表

How to validate react-select dropdown using use form hook in react

我是 yup 验证的新手,我正在使用以下选项填充 react-select 下拉列表。现在当我点击一个按钮试图验证是否有任何值被 select 编辑时。但它没有验证。非常感谢任何帮助。

const options = [
        { value: 'active', label: 'Active' },
        { value: 'inactive', label: 'In Active' },
        { value: 'deleted', label: 'Delete' },
 ];

<Select
  defaultValue={options[0]}
  isSearchable={false}
  className="react-dropdown"
  onChange={statusDropdownHandleChange}
  classNamePrefix="dropdown"
  options={options}
  name="status"
  {...register("status")}
/>


let schema = yup.object().shape({
    status: yup.object().shape({
      label: yup.string().required("status is required"),
      value: yup.string().required("status is required")
    })
 });

验证应该有效,但是如果您直接将 Selectreact-hook-form 一起使用,您将在选择 value/submitting 形式时遇到 error/value undefined 作为 Select 不公开输入的引用。因此,需要用Controller包裹Select来注册组件。

为了验证表单,如果在 Select 中允许 isClearable,则还有一种情况需要处理,其中值将是 null 而不是 {label: undefined, value: undefined},因此需要在状态验证结束时添加 .nullable().required()

验证

const schema = yup.object().shape({
  status: yup
    .object()
    .shape({
      label: yup.string().required("status is required (from label)"),
      value: yup.string().required("status is required")
    })
    .nullable() // for handling null value when clearing options via clicking "x"
    .required("status is required (from outter null check)")
});

形式与反应-select

<form onSubmit={handleSubmit(onSubmit)}>
    <Controller
        name="status"
        control={control}
        render={({ field }) => (
        <Select
            // defaultValue={options[0]}
            {...field}
            isClearable
            isSearchable={false}
            className="react-dropdown"
            classNamePrefix="dropdown"
            options={options}
        />
        )}
    />
    <p>{errors.status?.message || errors.status?.label.message}</p>
    <input type="submit" />
</form>

Here is the codesandbox