Home > Back-end >  How do I get my error message to go away after form validation in react js?
How do I get my error message to go away after form validation in react js?

Time:12-24

I have a simple login form that intakes user email and user password, the goal is to have an error message pop up directly under the input field, as well as add a red border around the input only if it's left blank or the pattern is wrong. Only one of my input fields is performing properly. (The input fields seem to be dependent of each other? )Any help would be appreciated !

The other input field is getting the red border removed once the password meets the requirements however, the error message remains. The goal is to have both the red border removed and the error message removed

class Login extends Component {
  constructor(props) {
    super(props);

    this.emailInput = React.createRef();
    this.passwordInput = React.createRef();

    this.state = {
      email: "",
      password: "",
      emailError: false,
      passwordError: false,
    };
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleInputChange = this.handleInputChange.bind(this);
    this.validate = this.validate.bind(this);
  }

  handleInputChange(e) {
    const { value, name } = e.target;
    this.setState({ [name]: value });
    console.log(value);
  }

  validateEmail(userEmail) {
    const emailPattern = /^[a-zA-Z0-9._-] @[a-zA-Z0-9.-] \.[a-zA-Z]{2,4}$/;
    return emailPattern.test(userEmail);
  }

  validatePassword(userPassword) {
    const passwordPattern =
      /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*])(?=.{8,})/;
    return passwordPattern.test(userPassword);
  }

  styleBorderEmail(emailInput, styles) {
    this.emailInput.current.style.border = styles;
  }

  styleBorderPassword(passwordInput, styles) {
    this.passwordInput.current.style.border = styles;
  }

  validate() {
    let emailError = this.email;
    let passwordError = this.password;

    if (!this.validateEmail(this.state.email)) {
      emailError = "email not valid";
      this.styleBorderEmail(this.emailInput, "1px solid red");
    } else {
      this.styleBorderEmail(this.emailInput, "1px solid black");
    }
    if (!this.validatePassword(this.state.password)) {
      passwordError = "password not valid";
      this.styleBorderPassword(this.passwordInput, "1px solid red");
    } else {
      this.styleBorderPassword(this.passwordInput, "1px solid black");
    }
    if (emailError || passwordError) {
      this.setState({ emailError, passwordError });
      return false;
    }
    return true;
  }

  handleSubmit(e) {
    e.preventDefault();
    const isValid = this.validate();

    if (isValid) {
      alert("successful submit");

      // clears the form after it's been submitted
      this.setState({
        email: "",
        password: "",
        emailError: false,
        passwordError: false,
      });
    }
  }

  render() {
    return (
      <div className="login-component">
        <div className="login-container">
          <h2>Welcome Back!</h2>
          <br />
          <form onSubmit={this.handleSubmit}>
            <div className="login-group">
              <label htmlFor="email" className="login-label">
                Your email
              </label>
              <input
                className="login-input"
                type="text"
                name="email"
                id="email"
                placeholder="Enter your email"
                value={this.state.email}
                onChange={this.handleInputChange}
                onKeyUp={this.validate}
                ref={this.emailInput}
              />
              {this.state.emailError && (
                <span className="error-login">
                  Please enter a valid email address
                </span>
              )}
            </div>
            <div className="login-group">
              <label htmlFor="password" className="login-label">
                Password
              </label>
              <input
                className="login-input"
                type="password"
                name="password"
                id="password"
                placeholder="Enter your password"
                value={this.state.password}
                onChange={this.handleInputChange}
                onKeyUp={this.validate}
                ref={this.passwordInput}
              />
              {this.state.passwordError && (
                <span className="error-login">Please enter a password</span>
              )}
            </div>
            <div>
              <button type="submit" className="login-btn">
                Login
              </button>
            </div>
          </form>
        </div>
      </div>
    );
  }
}

export default Login;

CodePudding user response:

You need to add one line code this.setState({ emailError: "", passwordError: "" }); in validate function before returning true.

New validate function looks like this

validate() {
    let emailError = this.email;
    let passwordError = this.password;

    if (!this.validateEmail(this.state.email)) {
      emailError = "email not valid";
      this.styleBorderEmail(this.emailInput, "1px solid red");
    } else {
      this.styleBorderEmail(this.emailInput, "1px solid black");
    }
    if (!this.validatePassword(this.state.password)) {
      passwordError = "password not valid";
      this.styleBorderPassword(this.passwordInput, "1px solid red");
    } else {
      this.styleBorderPassword(this.passwordInput, "1px solid black");
    }
    if (emailError || passwordError) {
      this.setState({ emailError, passwordError });
      return false;
    }
    this.setState({ emailError: "", passwordError: "" }); // New line added
    return true;
  }
  • Related