Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

355
Visualizações
REACT- How do I raise a warning if a specific input field is empty with Yup?

I'm creating a multi step form and I want to raise an error if my field 'title' and invited[0].name( at least one invited should be written) are not filled in my form such as 'this field is required' in red under the input box. I use Yup but doesn't seem working... Any ideas ?

export default function Information() {
  const [userData, setUserData] = useState({});
  const handleChange = (e) => {
    const { value, checked } = e.target;
    setUserData((userData) => ({
      ...userData,
      [value]: checked
    }));
  };

  return (
    <div className="flex flex-col ">
      <div>
        Title :
        <input
          onChange={handleChange}
          value={userData["title"]}
          name="title"
          placeholder="Title"
        />
      </div>
      ...
  );
}

In validation.js :

import * as Yup from "yup";
import menus from "../data/menus.json";
const {
  menus: { title, invited }
} = menus;

export default [
  Yup.object().shape({
    [title]: Yup.string().required(`Title required`),
    [invited.name]: Yup.string().required(`At least one participant required`)
  })
];

menus.json:

{
  "menus": [
    {
      "id": "Menu1",
      "title": "Soup",
      "price": 4,
      "invited": [
        {
          "name": "Jose Luis",
          "location": "LA"
        },
        {
          "name": "Smith",
          "location": "New York"
        }
      ]
    },
    ...
}

Here is my sandboxLink

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

  • You have to use Yup.array() to define the schema for the array (invited) and .of() to target each item of the array (which is an object in your case).

Change the validation.js to

import * as Yup from "yup";
import menus from "../data/menus.json";
const {
  menus: { title, invited }
} = menus;

export default Yup.object().shape({
        title: Yup.string().required(`Title required`),
        invited: Yup.array()
            .of(
                Yup.object().shape({
                    name: Yup.string().required('Required') // these constraints take precedence
                })
            )
            .required('At least one participant required') // these constraints are shown if and only if inner constraints are satisfied
            .min(1, 'At least one participant required'),
    });
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda