React form hooks How to validate select option
Asked Answered
E

4

12

I am working with react hooks and to validate my form fields I am using react-hook-form as it is the best option for now

SO to validating my normal input fields I am doing just ref={register({ required: true })} then on submit it is checking for errors as I am importing errors from react-hook-form

But when I am doing same for select field it is not checking the error object

This is what I am doing

<label htmlFor="func" className="form_label">
      Select function
    </label>
    <select name="func" ref={register({ required: true })}>
      <option selected disabled>
        Select function
      </option>
      <option value="5">Function 2</option>
      <option value="6">Function 3</option>
    </select>
    {errors.func && (
      <div>
        <span>Function is required</span>
      </div>
    )}

I don't know what I am missing

My actual code is with dynamic data

so I am looping over it like this

<Form.Control as="select" custom>
                    <option disabled selected>Select role</option>
                    {loading === false &&
                    data.get_roles.map((li) => (
                    <option value={li.user_type_id}> 
                    {li.user_type}</option>
        ))}
            </Form.Control>

React hook form

Endurance answered 25/6, 2020 at 11:53 Comment(3)
I think you are missing a default select with empty value=""Suint
@Suint I have tried everyu thing could you help me with some codeEndurance
take a look this CSB: codesandbox.io/s/infallible-tereshkova-x65qr?file=/src/App.jsSuint
N
18

try this code. I tried and it worked fine:

<label htmlFor="func" className="form_label">
  Select function
</label>
<select name="func" 
  ref={register({
     required: "select one option"
  })}>
  <option value=""></option>
  <option value="5">Function 2</option>
  <option value="6">Function 3</option>
</select>
{errors.func && <p style={{color:'red'}}> {errors.func.message}</p> }
Neela answered 5/7, 2020 at 22:31 Comment(5)
It is not working could you please share code sandboxEndurance
I hope this will help you code sandboxNeela
But where is a validation? You just set the select field as required.Yeanling
I stoped to work with React 2 years ago. I can't remember how it works properly. But I guess that the useForm from react-hook-form does the validation when the register together required is put inside select tag.Neela
<select {...register("func", { required: true })}Margaritamargarite
O
3
//This Works for me
import React from 'react'
import { useForm } from "react-hook-form";

function Test() {
    const { register, handleSubmit, formState: { errors } } = useForm();
    const onSubmit = data => console.log(data);
  return (
    <div>
        
        <form onSubmit={handleSubmit(onSubmit)}>
                <select
                  className="custom-select"
                  id="selectmethod"
                  defaultValue=""
                  name="exampleRequired"
                  {...register("exampleRequired", { required: true })}
                >
                  <option value="" disabled>Select Option</option>
                  <option  value="1">Blue</option>
                  <option  value="2">Red</option>
                </select>
                {errors.exampleRequired && <span className="formError errorMssg">This field is required</span>}
                <br/>
                <button type="submit" >SUBMIT </button>
                </form>
              </div>
  
  )
}

export default Test
Outbreak answered 20/1, 2023 at 8:7 Comment(0)
E
0

I think that I good way to validate forms is with yup. It gives you a lot of tools for validation and its integration with RHF is seamlessly: How to integrate yup with react-hook-form

import React from "react";
import ReactDOM from "react-dom";
import { useForm } from "react-hook-form";
import * as yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";

const schema = yup.object().shape({
  mySelect: yup.string().notOneOf([""], "You must select an option!")
});

function MyForm() {
  const {
    register,
    handleSubmit,
    formState: { errors }
  } = useForm({
    defaultValues: {
      mySelect: ""
    },
    resolver: yupResolver(schema)
  });
  const onSubmit = (data) => console.log(data);
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <select {...register("mySelect")}>
        <option value="" disabled>
          Select option
        </option>
        <option value="1">Option 1</option>
        <option value="2">Option 2</option>
      </select>
      <button type="submit">Submit </button>
      {errors.mySelect && <p className="error">{errors.mySelect.message}</p>}
    </form>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<MyForm />, rootElement);

Sandbox: Simple select validation with yup

Effluvium answered 21/1, 2023 at 16:27 Comment(0)
R
0

You can also use multi-select select option

              <select {...register("interests", {
                            required: 'interests is required'
                        })}
                        multiple
                    >
                        <option value="HTML">HTML</option>
                        <option value="CSS">CSS</option>
                        <option value="REACT">REACT</option>
                        <option value="VUE">VUE</option>
              </select>
              <small className="error">{errors?.interests?.message}</small>
Reservoir answered 7/11, 2023 at 10:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.