带有react-hook-form的reactjs中的表单验证问题

Form validation problem in reactjs with react-hook-form

我正在尝试使用 react-hook-form 进行表单验证。它工作正常,但有一个问题:它不检查输入类型。我希望用户只输入 URL 地址,但是这个东西将其验证为简单文本。我哪里弄错了?

function EditAvatarPopup({ isOpen, onClose, onUpdateAvatar, submitButtonName }) {

  const { register, formState: { errors }, handleSubmit } = useForm();
  const [link, setLink] = useState('');

  function handleInput(e) {
    setLink(e.target.value)
  }

  function handleSubmitButton() {
    console.log(link)
    onUpdateAvatar({
      avatar: link
    });
  }

  return (
    <PopupWithForm 
      name="change-avatar"
      title="Update avatar" 
      submitName={ submitButtonName }
      isOpen={ isOpen }
      onClose={ onClose }
      onSubmit={ handleSubmit(() => handleSubmitButton() ) }
    >
      <label htmlFor="userAvatar" className="form__form-field">
        <input 
          id="userAvatar" 
          type="url"
          { ...register('userAvatar', { 
            required: "Enter URL link",
            value: link 
          }) 
          } 
          placeholder="url link"
          className="form__input" 
          onChange={ handleInput }
        />
        { errors.userAvatar && (<span className="form__error">{ errors.userAvatar.message }</span>) }
      </label>
    </PopupWithForm>
  );
}

看起来 type="url" 不起作用,但我不明白为什么

这是一个最小的工作示例:https://codesandbox.io/s/react-hook-form-js-forked-ml3zx?file=/src/App.js

我建议不要覆盖 onChange 道具,而不是使用 const [link, setLink] = useState(''); 你可以使用 const link = watch('userAvatar').

您可以删除 value 属性,没有必要:

<input 
  id="userAvatar" 
  type="url"
  { ...register('userAvatar', { 
      required: "Enter URL link",
      value: link //⬅️ Remove that line
    }) 
  } 
  placeholder="url link"
  className="form__input" 
  onChange={ handleInput } //⬅️ Remove that line 
/>

React Hook Form - Watch API