Bhawna Saroha
Bhawna Saroha

Reputation: 633

How to validate select input field using React Hook Form?

I'm trying to validate a form made using form fields from React MD by using React Hook Form. The text input fields are working fine.

But the validations aren't working on the select field. Here is the code:

<Controller
  control={control}
  name="salutation"
  defaultValue=""
  rules={{ required: "Salutation is required" }}
  disabled={isSubmitting}
  render={(props) => (
     <Select
       id="salutation"
       {...props}
       label="Salutation"
       options={SALUTATION_ITEMS}
       value={salutationValue}
       onChange={(e) => handleSalutationChange(e)}
       disableLeftAddon={false}
       rightChildren={
          <RiArrowDownSFill className="dropDownArrow" />
       }
     />
   );
  }}
/>

The error persists even after the user selects a value:

{errors.salutation && (
  <div className="validation-alert msg-error ">
    <p>{errors.salutation.message}</p>
  </div>
)}

I'm probably missing something or doing something wrong.

Upvotes: 1

Views: 1357

Answers (1)

Ajeet Shah
Ajeet Shah

Reputation: 19823

I think you are missing props.value and props.onChange(e) and you may not need handleSalutationChange(e):

<Controller
  control={control}
  name="salutation"
  defaultValue=""
  rules={{ required: "Salutation is required" }}
  disabled={isSubmitting}
  render={(props) => (
     <Select
       id="salutation"
       {...props}
       label="Salutation"
       options={SALUTATION_ITEMS}
       value={props.value} // This one: props.value
       onChange={(e) => {
         props.onChange(e)   // I think you are missing this
         handleSalutationChange(e) // NOT Needed ?
       }}
       disableLeftAddon={false}
       rightChildren={
          <RiArrowDownSFill className="dropDownArrow" />
       }
     />
   );
  }}
/>

Upvotes: 3

Related Questions