Dileep
Dileep

Reputation: 515

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")
    })
 });

Upvotes: 2

Views: 20554

Answers (1)

Mic Fung
Mic Fung

Reputation: 5692

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

Upvotes: 11

Related Questions