【问题标题】:Make field required if its select dropdown has more than an option如果其选择下拉列表有多个选项,则将字段设为必填
【发布时间】:2022-11-03 22:19:56
【问题描述】:

我正在使用 react-hook-form 和背心解析器进行验证。我的代码是这样的:

const validationSuite = create((data = {}) => {
  if(department select has more than one value) {
    test('department', 'department', () => {
      enforce(data.department).isNotEmpty();
      enforce(data.department).isString();
    });
  }
});

const {register, reset, setValue, handleSubmit, formState: {errors}} = useForm<MyType>({
    resolver: vestResolver(validationSuite)
  });

<label htmlFor="department" className="form-label">Department</label>
            <select
              {...register("departmentId")}
              id="department"
              className="form-select"
            >
              <option value="">Select...</option>
              {departments?.map((entry, index) => {
                return <option key={index} value={entry.id}>{entry.name}</option>
              })}
            </select>

基本上,如果部门数组为空/选择项只有值为“”的选项,我想将此字段设为必需。

这可能吗?如果是这样,怎么做?

谢谢。

【问题讨论】:

    标签: reactjs react-hook-form


    【解决方案1】:

    将属性required 设置为select 字段,并设置一个逻辑是否需要departments.length == 0

    当然这应该在form 标签内

    <select
              {...register("departmentId")}
              id="department"
              required={departments.length == 0}
              className="form-select"
            >
    // rest of the code
    

    Working sandbox

    【讨论】:

    • 我希望在validationSuite 中完成此验证。
    猜你喜欢
    • 2022-06-23
    • 2015-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多