【问题标题】:How to validate react-select dropdown using use form hook in react如何在反应中使用表单挂钩来验证反应选择下拉列表
【发布时间】:2021-09-21 14:43:08
【问题描述】:

我是 yup 验证的新手,我正在使用以下选项填充 react-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")
    })
 });

【问题讨论】:

    标签: reactjs react-hooks yup react-hook-form


    【解决方案1】:

    验证应该可以工作,但是如果您直接使用Selectreact-hook-form,则在选择值/提交表单时会遇到错误/值未定义,因为Select 不会公开输入的参考。因此,您需要将SelectController 包裹起来才能注册组件。

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

    验证

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

    带有 react-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

    【讨论】:

    • 非常感谢,麦克风。我花了很多时间。
    • 我从未如此重视 StackOverflow 的响应。 react-hook-form 官方网站(link)上有一个非常模糊的描述“......如果组件没有公开输入的引用,......”并且您对这个问题的回答非常清楚我。我在这方面花了很多时间。谢谢你的好意。上帝保佑你!
    • 如果 select 是 multipe ?它会是数组而不是对象
    猜你喜欢
    • 2021-09-21
    • 2020-10-15
    • 2023-01-17
    • 1970-01-01
    • 2020-03-04
    • 1970-01-01
    • 2021-08-17
    • 2021-09-23
    • 1970-01-01
    相关资源
    最近更新 更多