Sign in
Log inSign up

How to deal with Form input validation?

Mrudang Shah's photo
Mrudang Shah
·May 9, 2019

My signup page is as follow. But i can get validation only for email field. For other rest of the two fields like username and password it is not working. And when a form is submitted successfully from server side then also an alert message of Form has errors. is displaying instead of Form submitted

Also, how can i make submit button disabled when there is no any input field is inserted ?

class Signup extends Component {
  constructor(props){
    super(props);
    this.state = {
      singupData: {
        username: '',
        email: '',
        password: '',
        errors: {}
      }
    }
    this.handleSignup = this.handleSignup.bind(this);
  }

  handleValidation(){
    let fields = this.state.singupData;
    let errors = {};
    let formIsValid = true;

    //Username
    if(!fields["username"]){
       formIsValid = false;
       errors["username"] = "Cannot be empty";
    }

    if(typeof fields["username"] !== "undefined"){
       if(!fields["username"].match(/^[a-zA-Z]+$/)){
          formIsValid = false;
          errors["username"] = "Only letters";
       }        
    }

    //Email
    if(!fields["email"]){
       formIsValid = false;
       errors["email"] = "Cannot be empty";
    }

    if(typeof fields["email"] !== "undefined"){
       let lastAtPos = fields["email"].lastIndexOf('@');
       let lastDotPos = fields["email"].lastIndexOf('.');

       if (!(lastAtPos < lastDotPos && lastAtPos > 0 && fields["email"].indexOf('@@') == -1 && lastDotPos > 2 && (fields["email"].length - lastDotPos) > 2)) {
          formIsValid = false;
          errors["email"] = "Email is not valid";
        }
    }

   if (!fields["password"]) {
    formIsValid = false;
    errors["password"] = "Please enter your password.";
  }

  if (typeof fields["password"] !== "undefined") {
    if (!fields["password"].match(/^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%&]).*$/)) {
      formIsValid = false;
      errors["password"] = "Please enter secure and strong password.";
    }
  }

   this.setState({errors: errors});
   return formIsValid;
}

  handleChange(field, e){         
    let fields = this.state.singupData;
    fields[field] = e.target.value;       
    this.setState({fields});
  }

  authView() {
    let isRegister = this.props.isRegistered;
    if( isRegister === true ){
     return window.location.href = '/';
    } else{
      return this.signupView();
    }
  }

  handleSignup(event) {
    let that = this;
    const { SingupAction } = that.props;
    event.preventDefault();
    if(this.handleValidation()){
      alert("Form submitted");
    }else{
      alert("Form has errors.")
    }
    const data = new FormData(event.target);
    let signupInput = {
      username: data.get('username'),
      email: data.get('email'),
      password: data.get('password'),
    }
    that.setState({
      singupData: signupInput,
    })
    SingupAction(signupInput)
  }

  signupView = () => {
    const { pristine, submitting } = this.props
    return (
      <section id="user_login">
        <div className="close_btn">
          <a href="javascript:void(0)" className="trans" title="Close">
            <ion-icon name="close"></ion-icon>
          </a>
        </div>
        <div className="container">
          <div className="inner_userlogin">
            <div className="signin_block">
              <div className="logo">
                <a href="#" className="trans" title="THEPlannerWIRE"><img src={siteurl + IMAGE.logoWhite} alt=""/></a>
              </div>
              <h1>Create your account</h1>
              <form onSubmit={this.handleSignup}>
              <ul>
                <li>
                  <div className="custom_group">
                    <input type="text" className="trans login_input" title="Username" name="username" placeholder="Username" onChange={this.handleChange.bind(this, "username")} value={this.state.singupData["username"]}/>
                  </div>
                </li>
                <li>
                   <div className="custom_group">
                    <input type="email" className="trans login_input" title="Email address" name="email" placeholder="Email address" onChange={this.handleChange.bind(this, "email")} value={this.state.singupData["email"]}/>
                  </div>
                </li>
                <li>
                  <div className="custom_group">
                    <input type="password" className="trans login_input" title="Set your password" name="password" placeholder="Set your password" value={this.state.singupData.password} onChange={this.handleChange.bind(this, "password")}/>
                    <span className="req">Minimum 8 characters</span>
                  </div>
                </li>
                <li className="sbt_btn">
                  <button className="trans white_bg" disabled={pristine || submitting}>SIGN UP</button>
                </li>
                <li>
                  <div className="custom_group">
                    <p>Already have an account? <a href={'/login'} className="trans" title="Sign In">Sign In</a>.</p>
                  </div>
                </li>
              </ul>
              </form>
            </div>
          </div>
        </div>
      </section>
    )
  }

  render() {
    return (
      <div>{this.authView()}</div>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    isRegistered: state.signup.isRegistered,
  };
}

const mapDispatchToProps = dispatch => ({
  SingupAction: (signupInput) => { dispatch(SingupAction(signupInput)) },
})

export default connect(mapStateToProps, mapDispatchToProps)(Signup);
Hassle-free blogging platform that developers and teams love.
  • Docs by Hashnode
    New
  • Blogs
  • AI Markdown Editor
  • GraphQL APIs
  • Open source Starter-kit

© Hashnode 2024 — LinearBytes Inc.

Privacy PolicyTermsCode of Conduct