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

89
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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