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

91
Vistas
React validate input field using errors array

I'd like to apply a few validation rules to an HTML input field, and add the error message to the errors state array each time the check doesn't go through.

<input
  name="email"
  type="email"
  value={ email }
  placeholder="Type your email address here..."
  onChange={ handleChange }
/>
<button
  className="Form_Submit"
  onClick={ handleSubmit }
>
  <i className="fas fa-arrow-right" />
</button>
handleSubmit() {
  const {
    values: {
    email = '',
    errors = []
  } = {}
} = this.state;

if (!validateEmailAddress(email)) {
  errors.push('Please provide a valid e-mail address');
}

if (isEmpty(email)) {
  errors.push('Email address is required');
  }
}

Updated:

if (!validateEmailAddress(email)) {
  this.setState({
    errors: [...errors, 'Please provide a valid e-mail address']
  });
}

if (isEmpty(email)) {
  this.setState({
    errors: [...errors, 'Email address is required']
  });
}

The following syntax doesn't take the number of component update times, therefore I end up with 4-8 messages each time I click the submit button. Are there ways to handle the input field validation in the errors array (to display all messages in the end) to push just a single value to an array, and then remove it?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I think you are missing setting state.

handleSubmit() {
  const {
    values: {
      email = '',
      errors = ''
    } = {}
  } = this.state;

  if (!validateEmailAddress(email) && !errors.contains('Please provide a valid e-mail address')) {
    errors.push('Please provide a valid e-mail address')
  }

  if (!!email && !errors.contains('Email address is required')) {
    errors.push('Email address is required');
  }

  setValues({...rest, errors});
  if (!errors.length) { 
    doFunc(); //your expected function
  }
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can refer to this code https://www.codegrepper.com/code-examples/javascript/push+unique+values+in+array+javascript

const myArray = ['a', 1, 'a', 2, '1'];
const unique = [...new Set(myArray)]; // ['a', 1, 2, '1']

Set in javascript stores unique values so it will be helpful. You can apply the below code

const errorSet = new Set([...this.state.errors]);
if (!validateEmailAddress(email)) {
  errorSet.add('Please provide a valid e-mail address');
}

if (isEmpty(email)) {
  errorSet.add('Email address is required');
}
this.setState({
   errors: [...errorSet]
});
about 4 years ago · Juan Pablo Isaza 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