簡體   English   中英

基於是否選中另一個復選框,文本字段的 React-hook-form 條件驗證?

[英]React-hook-form conditional validation of text field, based on if another checkbox is checked?

我正在嘗試向文本字段添加驗證規則,如果選中表單中的單獨復選框,則該字段必須是非空字符串才能提交表單。

這是我到目前為止所擁有的鏈接: https : //codesandbox.io/s/magical-hypatia-n7o5w

我需要表單(“tiger_type”)中的最終文本輸入,以便僅在選中帶有 id 'tiger' 的復選框輸入時才需要輸入值。

我是 react 和 react-hooks-form 的新手,因此將不勝感激。 提前致謝。

使用react-hook-form提供的回調函數的驗證對象。 完全有效的解決方案https://codesandbox.io/s/admiring-morning-ljnvk?file=/src/App.js

import { useForm } from 'react-hook-form';
// ... your component implementation 
const { getValues, getValues } = useForm(); 

return (
  <form onSubmit={handleSubmit}>
    <input ref={register} name="username" />
    <input
      ref={register({
        validate: {
          required: value => {
            if (!value && getValues('username')) return 'Required when username is provided';
            return true;
          },
        },
      })}
      name="email"
      type="text"
    />
 </form>
);

注意:在撰寫本文時,react-hook-form https://react-hook-form.com/api#register 的v5 和 v6 支持此解決方案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM