Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate a React select value using Yup validation?

I'm currently using react-select and Yup for validation , code looks like this for the react select component

import React, { useState, useMemo } from "react";
import Select from "react-select";
import countryList from "react-select-country-list";

function CountrySelector({ register }) {
  const [value, setValue] = useState("");
  const options = useMemo(() => {
    return countryList().getData();
  }, []);

  const changeHandler = (value) => {
    setValue(value);
    console.log(value);
  };
  // console.log(countryList().getData())
  return (
    <>
      <div className="mb-2.5">
        <Select
          placeholder="Select a Country"
          className=""
          options={options}
          value={value}
          {...register}
          onChange={changeHandler}
        />
      </div>
    </>
  );
}

export default CountrySelector;

my schema looks like this :

const schema = yup.object().shape({
  email: yup
    .string()
    .required("This field is required")
    .email("Please enter a valid email address"),
  password: yup.string().required("This field is required"),
  phoneNumber: yup.string().required("This field is required"),
  username: yup.string().required("This field is required"),
  selectedCountry: yup.object().shape({
    value: yup.string().required("Required"),
    label: yup.string().required("Required"),
  }),
  tosagree: yup
    .bool() // use bool instead of boolean
    .oneOf([true], "You must accept the terms and conditions"),
});

const RegistrationForm = () => {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
  });

  const auth = useSelector((state) => state.auth);

  const [showPassword, setShowPassword] = useState(false);

  const dispatch = useDispatch();
  let navigate = useNavigate();
  const togglePasswordHandler = () => setShowPassword((state) => !state);

  const registrationHandler = (data) => {
    console.log(data);
    data = {
      ...data,
      country: selectedCountry.value,
    };

    // console.log(JSON.stringify(data));
    //  dispatch(authActions.register(data));
    registerNewUser(data);
  };

  const registerNewUser = async (userData) => {
    try {
      console.log(` user Data is ${JSON.stringify(userData)}`);
      const { data, status } = await httpClient.post("/usersv2/", userData, {
        validateStatus: () => true,
      });
      console.log(data);
      console.log(status);
      if (status === 201) {
        navigate("/confirm-email");
      }
    } catch (err) {
      console.log(err);
    }
  };

and code for the country selector is this :

<div className="mb-2.5">
  <CountrySelector register={{ ...register("selectedCountry") }} />

  <ErrorMessage message={errors?.selectedCountry?.message} />
</div>

even after defining the countrySelected as an object in the schema , errors don't show if i have no value or even if i have a value in , any help ?

like image 739
Mohamed Nabil Avatar asked Oct 14 '25 14:10

Mohamed Nabil


1 Answers

selectedCountry: Yup.string()
        .required()
        .oneOf(["usa", "mexico"])
        .label("Selected Country"),

You can validate select options in yup as this especially .oneOf(["usa", "mexico"])

sample working code: https://codesandbox.io/s/react-hook-form-js-forked-rezdf8?file=/src/App.js

like image 102
Saroj Shrestha Avatar answered Oct 18 '25 07:10

Saroj Shrestha



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!