简体   繁体   中英

Make a field required depending on the value of a radio button

I am using react-hook-form for my project. I am trying to make a field required depending on the selected value in the radio button. I am using ant design and styled component so maybe this example is not as explicit.

                         <Controller
                                control={control}
                                rules={{
                                    required: requiredField(watch, fld),
                                }}
                                name={field}
                                defaultValue={v || ''}
                                render={({ field: { onChange, value } }) => (
                                    <Radio.Group
                                        defaultValue={matchDataInForm(field)}
                                        disabled={formType === 'read' ? true : readOnly}
                                        value={value}
                                        onChange={(e) => onChange(e.target.value)}
                                        {...register(field, {
                                            validate: { required: () => getValues().field },
                                        })}
                                    >
                                        {items.length > 0
                                            ? items.map((item) => (
                                                    <div key={item.id}>
                                                        <Radio value={item.id}>{item.label}</Radio>
                                                    </div>
                                              ))
                                            : null}
                                    </Radio.Group>
                                )}
                            />

The issue now that I have, it is working, but basically when I submit the form the radio button value is not taken into account

You can use schema definitions to define the validation in a more declarative (and maintainable) way. You can also switch the schemas on the fly based on checkboxes or radio boxes being set to a certain value.

Here's a fully working example that expects a field to be set ONLY if a checkbox is set to true: https://codesandbox.io/s/dynamic-schema-with-react-hook-form-forked-ufgt87?file=/src/DynamicForm.tsx

The core of this code is here:

  const resolver = useMemo(
    () => zodResolver(!isChecked ? formSchema : formSchemaWithEmail),
    [isChecked]
  );
  const {
    register,
    handleSubmit,
    formState: { errors }
  } = useForm({
    resolver: resolver
  });

Then you don't have to define any rules on any fields. The validation rules are inside the formSchema and formSchemaWithEmail objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM