【问题标题】:React-redux password strength bar not workingReact-redux 密码强度栏不起作用
【发布时间】:2018-10-23 04:47:51
【问题描述】:

您好,我想为我的密码添加一个进度强度条,但不知道如何在反应中链接“eventlistner”。到目前为止,该代码可用于检查密码正则表达式,但不确定如何添加密码强度条。我不知道如何在反应中使用 addEventListener。

请查看我的代码并告诉我我做错了什么?谢谢。

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)

【问题讨论】:

  • 你的进度元素应该链接到密码检查函数:&lt;progress max="100" value={this.getPasswordStrength()} id="strength"&gt;getPasswordStrength()函数应该查看密码状态,计算它的强度然后返回。不要在 React 中直接进行 DOM 操作,这会导致问题。

标签: javascript reactjs redux passwords


【解决方案1】:

这是您可以在组件中进行的一些更改,

进行中的组件,

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

在密码输入中,

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

在你的构造函数中,初始化password_strength和绑定方法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);
    }

最后是你的 checkPassword 方法,

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});
}

如果还是不行,请在codepen上分享你的工作代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-13
    • 1970-01-01
    • 2021-08-14
    相关资源
    最近更新 更多