Home > OS >  React validate input field using errors array
React validate input field using errors array

Time:01-25

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?

CodePudding user response:

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

CodePudding user response:

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']
  •  Tags:  
  • Related