Jattsingh
Jattsingh

Reputation: 11

React-redux password strength bar not working

Hi I want to add a progress strength bar for my password but not sure how to link an "eventlistner" in react. So far the code works for checking the password regex but not sure how to add the password strength bar. I don't know how to use addEventListener in react.

Please have a look at my code and tell me what am I doing wrong? Thanks.

import React from 'react'
import {connect} from 'react-redux'
import {registerUserRequest} from '../../actions/register'
import {loginError} from '../../actions/login'

class Register extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      user_name: '',
      contact_number: '',
      email_address: '',
      password: '',
      confirm_password: ''
    }
    this.updateDetails = this.updateDetails.bind(this)
    this.submit = this.submit.bind(this)
    this.validateEmail = this.validateEmail.bind(this)
    this.validatePassword = this.validatePassword.bind(this)
  }

  componentDidMount() {
    this.props.dispatch(loginError(''))
  }

  updateDetails(e) {
    this.setState({[e.target.name]: e.target.value})
  }

  submit(e) {
    e.preventDefault()
    e.target.reset()
    let {user_name, password, confirm_password, email_address, 
    contact_number} = this.state
    function confirmation (){
      if (confirm_password != password)
        return false
      else
        return true
    }

    const isEmail = this.validateEmail(email_address)
    const passwordsNotSame = (confirm_password != password)
    const isPass = this.validatePassword(password)

    if (!isEmail || passwordsNotSame) return 
    this.props.dispatch(loginError("Incorrect email/Passwords don't 
    match"))
    else if (!isPass) return this.props.dispatch(loginError('Password 
    strength must be 8 or above and must include atleast one number '))
    else return this.props.dispatch(registerUserRequest(this.state))
  }

  validateEmail(email) {
    var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|
    (".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-
    Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    var isValid = re.test(String(email).toLowerCase());
    // console.log('No joke', isValid)
    return isValid
  }

  validatePassword(pass) {
    var re = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
    var isPasswordValid = re.test(String(pass));
    return isPasswordValid
  }

  const pass = document.getElementById("password")
  pass.addEventListener('keyup', function() {
    checkPassword(pass.value)
  })

  checkPassword(password) {
    var strengthBar = document.getElementById("strength")
    var strength = 0;
    if (password.match(/[a-zA-Z0-9][a-zA-Z0-9]+/)) {
      strength += 1
    }
    if (password.match(/[~<>]+/)) {
      strength +=1
    }
    if (password.match(/[!@£$%^&()]+/)) {
      strength +=1
    } if (password.length > 5) {
    strength +=1
    }
    switch(strength) {
    case 0:
            strengthBar.value = 20;
            break
    case 1:
            strengthBar.value = 40;
            break
    case 2:
            strengthBar.value = 60;
            break
    case 3:
            strengthBar.value = 80;
            break
    case 4:
            strengthBar.value = 100;
            break
    }
  }

  render() {
    const {auth} = this.props
    return (
      <form onSubmit={this.submit}>
        <h1>Register</h1>
        <hr />
        <b>{auth.errorMessage && <span>{auth.errorMessage}</span>}</b>

        <div className="field is-horizontal">
          <div className="field-label is-normal">
            <label>Username</label >
          </div>
           <input   className="input is-medium"required placeholder="User 
    Name" type="text" name="user_name" onChange={this.updateDetails}/>
        </div>

        <div className="field is-horizontal">
          <div className="field-label is-normal">
            <label>Contact Number</label>
          </div>
          <input className="input is-medium"required placeholder="Contact 
    Number" type="text" name="contact_number" onChange=
    {this.updateDetails}/>
        </div>

          <div className="field is-horizontal">
            <div className="field-label is-normal">
              <label>Email Address</label>
            </div>
            <div className="field-body">
                <div className="field">
                  <input className="input is-medium"required 
    placeholder="Email Address" type="text" name="email_address" onChange=
    {this.updateDetails}/>
                </div>
            </div>
          </div>

        <div className="field is-horizontal">
          <div className="field is-horizontal">
            <label>Password</label>
            <progress max="100" value="0" id="strength"></progress>
          </div>
            <input className="input is-medium"required 
    placeholder="Password" type="password" name="password" onChange=
    {this.updateDetails}/>
        </div>
        <div className="field is-horizontal">
          <div className="field is-horizontal">
            <label>Confirm Password</label>
          </div>
            <input className="input is-medium"required 
    placeholder="Confirm Password" type="password" name="confirm_password" 
    onChange={this.updateDetails}/>
         </div>
        <input className="button is-primary" value="Register" 
    type="submit" />

      </form>
        )
    }
  }

  const mapStateToProps = ({auth}) => ({auth}) 

  export default connect(mapStateToProps)(Register)

Upvotes: 0

Views: 444

Answers (1)

Kishan Rajdev
Kishan Rajdev

Reputation: 1965

This are some changes you can make in your component,

In progress component,

<progress max="100" value={(this.state.password_strength * 20)} id="strength"></progress>

in password input,

<input className="input is-medium"required 
    placeholder="Password" type="password" name="password" onChange=
    {this.updateDetails} onKeyUp={this.checkPassword}/>

In your constructor, initializing password_strength and binding method checkPassword

    constructor(props) {
      super(props)
      this.state = {
        user_name: '',
        contact_number: '',
        email_address: '',
        password: '',
        confirm_password: '',
        password_strength: 0,
      }
      this.updateDetails = this.updateDetails.bind(this)
      this.submit = this.submit.bind(this)
      this.validateEmail = this.validateEmail.bind(this)
      this.validatePassword = this.validatePassword.bind(this)
      this.checkPassword = this.checkPassword.bind(this);
    }

and finally, your checkPassword method,

checkPassword(e) {
  const password = e.target.value;
  const password_strength = 0;
  var strength = this.state.password_strength;
  if (password.match(/[a-zA-Z0-9][a-zA-Z0-9]+/)) {
    strength += 1
  }
  if (password.match(/[~<>]+/)) {
    strength +=1
  }
  if (password.match(/[!@£$%^&()]+/)) {
    strength +=1
  } if (password.length > 5) {
  strength +=1
  }
  this.setState({password_strength: strength});
}

If still doesn't work, Please share your working code on codepen.

Upvotes: 1

Related Questions