Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate react-select dropdown using use form hook in react

I am new to yup validation, and I am populating the react-select dropdown with the below options. and now when I click on one button trying to validate if any value is selected or not. but it is not validating. any help is much appreciated.

const options = [
        { value: 'active', label: 'Active' },
        { value: 'inactive', label: 'In Active' },
        { value: 'deleted', label: 'Delete' },
 ];

<Select
  defaultValue={options[0]}
  isSearchable={false}
  className="react-dropdown"
  onChange={statusDropdownHandleChange}
  classNamePrefix="dropdown"
  options={options}
  name="status"
  {...register("status")}
/>


let schema = yup.object().shape({
    status: yup.object().shape({
      label: yup.string().required("status is required"),
      value: yup.string().required("status is required")
    })
 });
like image 742
Pioter Avatar asked Apr 24 '26 03:04

Pioter


1 Answers

The validation should be working but if you are using Select with react-hook-form directly, you will hit the error/value undefined when choosing value/submitting form as Select doesn't expose input's ref. Therefore, you need to wrap Select with Controller to register the component.

For validating the form, there is one more case to handle if you allow isClearable in Select where the value will be null instead of {label: undefined, value: undefined} so there is a need to add .nullable() and .required() at the end of status's validation.

validation

const schema = yup.object().shape({
  status: yup
    .object()
    .shape({
      label: yup.string().required("status is required (from label)"),
      value: yup.string().required("status is required")
    })
    .nullable() // for handling null value when clearing options via clicking "x"
    .required("status is required (from outter null check)")
});

form with react-select

<form onSubmit={handleSubmit(onSubmit)}>
    <Controller
        name="status"
        control={control}
        render={({ field }) => (
        <Select
            // defaultValue={options[0]}
            {...field}
            isClearable
            isSearchable={false}
            className="react-dropdown"
            classNamePrefix="dropdown"
            options={options}
        />
        )}
    />
    <p>{errors.status?.message || errors.status?.label.message}</p>
    <input type="submit" />
</form>

Here is the codesandbox

like image 152
Mic Fung Avatar answered Apr 29 '26 22:04

Mic Fung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!