How to create validation in different fields in the Reactjs form?

Asked

Viewed 119 times

0

How do I validate the form created with Reactjs according to what user reports in the fields?

Example:

<form>
  <label for="tipo_requisicao">Escolha uma opção:</label>
  <!-- Campo obrigatório -->
  <select name="tipo_requisicao" id="tipo_requisicao">
    <option value="Aumento">Aumento de Quadro</option>
    <option value="Substituição">Substituíção</option>
  </select>

  <!-- Campo obrigatório apenas se escolher a opção "Aumento" no input acima "tipo_requisicao" -->
  <textarea id="story" name="story" rows="5" cols="33"></textarea>
</form>

I am using React-Hook-Form for my Reactjs forms, but it can be any example or tip of how to do this, whether via YUP with Formik, or other.

  • Watch the video, see the documentation, it’s all there you need to know.

  • I appreciate the tip, but I didn’t have in the documentation the way to do it. I got it using Reactjs Conditional Rendering.

1 answer

0

I managed to do what I wanted using the Conditional Rendering .

Stayed like this:

<form>
  <label for="tipo_requisicao">Escolha uma opção:</label>
  <!-- Campo obrigatório -->
  <select name="tipo_requisicao" id="tipo_requisicao" ref={register({ required: true})}>
    <option value="Aumento">Aumento de Quadro</option>
    <option value="Substituição">Substituíção</option>
  </select>

  <!-- Campo obrigatório apenas se escolher a opção "Aumento" no input acima "tipo_requisicao" -->
  {tipo_requisicao === "Aumento" && 
    <textarea id="story" name="story" rows="5" cols="33" ref={register({ required: true})}></textarea>
  }
</form>

Because the textarea field is rendered only if the value of the requisica_type field is equal to the value "Increase", it will be mandatory only after it is rendered.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.