0

I want to implement validation for React form using react-hook-form. For input value I implemented this:

       <div className='input-group mb-3'>
          <Controller
              control={control}
              name={"email"} //  the key of json
              defaultValue={""}
              render={({ field }) => (
                  <input
                      {...field}
                      type="email"
                      className="form-control"
                      placeholder="Email"
                      aria-label="email"
                      onChange={(e) => field.onChange(e.target.value)}
                  />
              )}
          />
        </div>

For me it's not clear how I need to implement it for select menu:

            <div className='input-group mb-3'>
              <select
                className='form-control form-select'
                name='budget'
                id='budget'
                required=''
                data-msg='Please select your budget.'
              >
                <option value=''>Budget</option>                  
                <option value='budget3'>More than $500,000</option>
              </select>
            </div>

Wat is the proper way to implement it?

1 Answer 1

1

somethings like this works?

<Controller
  control={control}
  name="budget"
  rules={{
    budget: {
      required: "Required",
    },
  }}
  render={({ field }) => (
    <select name="budget" onChange={field.onChange} value={field.value}>
      <option value="">Please select your budget</option>
      <option value="budget3">More than $500,000</option>
      <option value="budget2">$250,000 - $500,000</option>
      <option value="budget1">$100,000 - $250,000</option>
      {/* more budgets */}
    </select>
  )}
/>;

control is destructured from useForm like so:

const { controls, register, setValue, ...moreEls } = useForm();
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, the code is working but there is no validation message. I opened a new question stackoverflow.com/questions/73351493/… Can you advise please?
You can destructure errors from useForm and display the errors.budget?.message somewhere in a DOM element like <label>{errors.budget?.message}</label>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.