首页 > 解决方案 > 使用材质 ui 时,表单元素上的多个验证不起作用

问题描述

我正在为我的网站 ui 使用材料 ui,并且还使用 react-hook-form。我的代码如下:

<TextField
            name="firstName"
            id="firstName"
            label="First Name"
            ref={register({ required: true, minLength: 6 })}
          />
          <div>
            {errors.firstName?.type === "required" && (
              <div className={classes.errorMsg}>First Name is required.</div>
            )}
            {errors.firstName?.type === "minLength" && (
              <div className={classes.errorMsg}>
                First Name length should be more than 6 characters.
              </div>
            )}
          </div>

我正在尝试对 firstName 元素应用多个验证,但只有“必需”有效。我输入任何小于 6 个字符的值,然后 react-hook-form 应该显示“minLength”错误,该错误不起作用。

请建议我这是 react-hook-form 的问题,或者我做错了申请。非常感谢。

标签: reactjsmaterial-uireact-hook-form

解决方案


您可以使用 inputRef 代替 ref

<TextField
    name="firstName"
    id="firstName"
    label="First Name"
    inputRef={register({ required: true, minLength: 6 })}
  />

推荐阅读