2
\$\begingroup\$

I was writing some validation logic for a React-native app and thought I had so many bools flying around in my code!

Is there any way to reduce redundancy in this code or is this the best that can be done?

_validatePhone() {
    if (!validate.validatePhone(this.state.phone)) {
      this.setState({ phoneError: true });
      return false;
    }
  return true;
}

_validateName() {
    if (!validate.validateName(this.state.name)) {
      this.setState({ nameError: true });
      return false;
    }
    return true;
  }

  _validateForm() {
    this._resetErrors(); // Reset errors before validating
    if (!this._validateName()) {
      return false;
    } else if (!this._validatePhone()) {
      return false;
    }
    return true;
  }
\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

_validateForm can be reduced to

_validateForm() {
    this._resetErrors(); // Reset errors before validating
    return this._validateName() && this._validatePhone();
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.