Shawn Sheehan
Shawn Sheehan

Reputation: 191

Validation React

How I would I use this validation without reduxForm. I know how it is done with reduxForm but the guy above me wants this built without ReduxForm. So Any ideas on how to achieve this?

onAddHistory = (field) => (response, index, value) => {
  const { history } = this.state;
  console.log(this.state);
  if (field === 'employerName' || field === 'description') {
    history[field] = response.target.value;
  } else if (field === 'roles') {
    history[field] = value;
  } else {
    history[field] = response.value;
  }
  this.setState({
    history: this.state.history,
  }
 }

isValid = () => {
  const errors = {};
  const regex = ***** to long to post

  if (!history.employerName || Validator.isNull(history.employerName)) 
   {errors.employerName = translations.translate('common', 
   'thisFieldIsRequired');}

this.setState({
  errors,
});

  return isEmpty(errors);
}

Then the errors would pass into the fields as Any ideas? Thank you ahead of time...

Upvotes: 1

Views: 83

Answers (1)

nbkhope
nbkhope

Reputation: 7474

I would use the following approach:

(1) Given an input component, attach an onChange event handler

(2) In the definition for the onChange event handler, pass your field information (such as name, value, etc) to some validation method.

(3) Determine the validation error from the output of your validation method and store it somewhere (e.g. component state).

You can use event.target.value, event.target.name, etc to get information about the target field.

Your if statements in the onAddHistory method seem a bit convoluted. Please keep in mind when you want to change the state of a component, you always need to create a new object and substitute it on top of the existing state using setState(). In other words, you should never mutate this.state directly.

SomeForm component example (only a snippet, not the whole thing):

onFruitChange = (event) => {
  let error = null;

  // Validations (refactor with a helper validation function)
  if (event.target.value === '') {
    // Given value was blank, but the field is required
    error = `${event.target.name} is a required field`;
  }
  else if (event.target.value.length < 3) {
    // Given value must be at least 3 characters
    error = `${event.target.name} must contain at least 3 characters';
  }
  // else if ... other validation conditions

  this.setState({ fruit: event.target.value, fruitError: error });
}

render() {
  return (
    // ...
    <input type="text" name="fruit" value={this.state.fruit} onChange={this.onFruitChange} />
  )
}

In the example above, this.state.fruitError will indicate whether you have a validation error (its value is the error description).

Upvotes: 1

Related Questions