複数項目のreact-hook-formのバリデーションエラーで詰まっている

実現したいこと

・項目1 = hoge1
・項目2 = hoge2
のtextfileがあって、

①送信ボタンをクリックしonSubmitでForm全体の値を送信する
②項目1と項目2のバリデーションが発火
入力内容は、
・項目1は入力されている
・項目2は空

*validatehoge2が発火
hoge2 のtextが赤色になる
下記項目

<Text control={control} name="hoge2" type="text" label="" rules={{ validate: validatehoge2 }} />


修正内容、
・項目1の入力内容を全て削除 => 空
・項目2は空

*validatehoge1のみが発火(hoge1の項目が修正されたので)
hoge2 のtextが赤色が消えない

*実現したいこと
ここでhoge2 のバリデーションも発火させて
hoge2のバリデーションエラーを消したい。

・onchangeでhoge1とhoge2が変更された時、
お互いのvalidateを実行する方法もあるが、
その方法だと、送信ボタンをクリック前にvalidateが発火され
UIにエラー表示が出てしまう。

発生している問題・分からないこと

ーーーーーーーーーーー

エラーメッセージ

error

1ーーーーーーーーーーーーーー

該当のソースコード

index.tsx(親CP)

1<FormProvider {...form}> 2 〜〜〜 3  <hoge/> 4</FormProvider>

hoge.tsx(子コンポーネント)

1export default function hoge() { 2 const { control} = useFormContext(); 3 return ( 4 <> 5 <div> 6 <Label>test</Label> 7 〜〜〜 8 </div> 9 <div spacing={1}> 10 <Label>複数項目</Label> 11 <Text 12 control={control} 13 name="hoge1" 14 type="text" 15 label="" 16 rules={{ validate: validatehoge1 }} 17 /> 18 <Text 19 control={control} 20 name="hoge2" 21 type="text" 22 label="" 23 rules={{ validate: validatehoge2 }} 24 /> 25 </div> 26 ) 27

text.tsx(孫コンポーネント)

1export function Text(props: any): JSX.Element { 2 return ( 3 <Controller 4 name={props.name} 5 control={props.control} 6 rules={props.rules} 7 render={({ field: { onChange, onBlur, value, ref }, fieldState }) => ( 8 <MuiTextField 9 label={props.label} 10 type={props.type} 11 error={fieldState.invalid} 12 helperText={props.helperText} 13 InputProps={props.InputProps} 14 value={value === null ? "" : value} 15 placeholder={props.placeholder} 16 onChange={onChange} 17 onBlur={onBlur} 18 inputRef={ref} 19 /> 20 )} 21 /> 22 ); 23}

validate.ts

1// hoge1のバリデーション 2export function validatehoge1(hoge1: string, form: any): string | undefined { 3 if(!hoge1&& !form.hoge2) { 4 return 5 } 6 if (!hoge1&& form.hoge2) { 7 return "「hoge1を入力してください。"; 8 } 9 if (hoge1&& _hoge1.length > 10) { 10 return "「hoge1の文字数が超えております。10文字以内で入力してください"; 11 } 12} 13 14// hoge2のバリデーション 15export function validatehoge2(hoge2: string , form: any): string | undefined { 16 if(!hoge2&& !form.hoge2) { 17 return 18 } 19 if (!hoge2 && form.hoge2) { 20 return "hoge2を入力してください。"; 21 } 22 if (hoge2 && _hoge2.length > 30) { 23 return "「hoge2の文字数が超えております。10文字以内で入力してください"; 24 } 25}

試したこと・調べたこと

上記の詳細・結果

ーーーーーーーーーーー

補足

ーーーーーーーーーーー

コメントを投稿

0 コメント