Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

334
Vistas
Wrong input validation

I want to validate all of my inputs in react My validation code looks like this:

let isValid = {
    name: false,
    address: false,
    postcode: false,
    phone: false,
    email: false
};

const validateInput = (e) => {
    let currentInput = e.target

    if (currentInput.name === 'name') {
        if (currentInput.value !== 'undefined' && currentInput.value.match(/^[a-zA-Z]+$/)) {
            isValid.name = true;
        } else {
            isValid.name = false;
        }
    }

    if (currentInput.name === 'address') {
        if (currentInput.value !== 'undefined') {
            isValid.address = true;
        } else {
            isValid.address = false;
        }
    }

    if (currentInput.name === 'postcode') {
        if (currentInput.value !== undefined && currentInput.value.match(/^[0-9]+[-]+[0-9]+$/) && currentInput.value.length > 4) {
            isValid.postcode = true;
        } else {
            isValid.postcode = false;
        }
    }

    if (currentInput.name === 'phone') {
        if (currentInput.value !== 'undefined' && currentInput.value.match(/^[0-9]+$/) && currentInput.value.length > 7) {
            isValid.phone = true;
        } else {
            isValid.phone = false;
        }
    }

    if (currentInput.name === 'email') {
        if (currentInput.value !== 'undefined' && currentInput.value.match(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)) {
            isValid.email = true;
        } else {
            isValid.email = false;
        }
    }

    console.log(isValid)
}

For example when i type correct value in "Name" isValid.name gets value true, then when i write somethink in "address" isValid.address gets true, but isValid.name false How to fix it?

{requiredInformations.map((el) => (
        <>
            <Label>{el.label}</Label>
            <Input type={el.type} name={el.name} required onChange={(e) => { getInputValue(e); validateInput(e) }} />
        </>
    ))}
about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

I suggest you try to use react-joi library for validation React-Joi-Validation Its easy and simple to use, and you can achieve what you are trying here in your code by just reading the first page on their npm package main page.

about 4 years ago · Santiago Trujillo Denunciar

0

You need to get yourself familiar with terms like "state" , "props", "component lifecycle", etc. Build a simple component using a guide on youtube, you can find plenty of them.

Meanwhile, here is a simple component that validates inputs:

function App() {
  const [name, setName] = React.useState('');
  const [address, setAddress] = React.useState('');

  const isValid = React.useMemo(() => {
    const result = {
      name: false,
      address: false,
    };

    if (name.match(/^[a-zA-Z]+$/)) {
      result.name = true;
    } else {
      result.name = false;
    }

    if (address !== '') {
      result.address = true;
    } else {
      result.address = false;
    }

    return result;
  }, [name, address]);

  return (
    <div>
      <input
        placeholder="Name"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />

      {isValid.name ? <p>Name is valid</p> : <p>Name is invalid</p>}

      <br />

      <input
        placeholder="Address"
        value={address}
        onChange={(e) => setAddress(e.target.value)}
      />

      {isValid.address ? <p>Adress is valid</p> : <p>Adress is invalid</p>}
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>


<div id="root">
</div>

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda