如何在反应中使用表单钩子验证反应选择下拉列表

Dil*_*eep 2 reactjs yup react-hooks react-hook-form

我是 yup 验证的新手,我正在使用以下选项填充反应选择下拉列表。现在,当我单击一个按钮时,尝试验证是否选择了任何值。但它没有验证。任何帮助深表感谢。

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")
    })
 });
Run Code Online (Sandbox Code Playgroud)

Mic*_*ung 11

验证应该有效,但如果您直接使用Selectwith react-hook-form,则在选择值/提交表单时会遇到错误/值未定义,因为Select不会公开输入的引用。因此,您需要Select使用Controller包装来注册组件。

为了验证表单,如果您允许使用isClearableSelect的位置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)")
});
Run Code Online (Sandbox Code Playgroud)

带有反应选择的形式

<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>
Run Code Online (Sandbox Code Playgroud)

这是代码和框