title: Regex pattern for username in react form
body: <p>I have made a react form, for usernames and passwords, and have a regex form to validate them. </p>
  
  <p>I have a set state, to first set the value, then I pass in a callback to setState to then verify that the username is correct.</p>
  
  <pre><code>onChange={(e) =&gt; this.setState({username: e.target.value}, this.usernameValidator(this.state.username))}
  </code></pre>
  
  <p>I use the setState callback because I know it will be called each time something is changed, I'm not sure if I should call the method separately?</p>
  
  <p>here is my handler </p>
  
  <pre><code>  usernameValidator = (username) =&gt;{
  var usernameRegex = /^[a-zA-Z0-9]+([a-zA-Z0-9](_|-| )[a-zA-Z0-9])*[a-zA-Z0-9]+$/;
  if(usernameRegex.test(username)){
    this.setState({
      isUsernameCorrect: true
    })
  }else{
    this.setState({
      isUsernameCorrect: false
    })
  }
    console.log(this.state.isUsernameCorrect)
  }
  </code></pre>
  
  <p>my issue is that, whenever a user types for example 5 characters, which is passable to the regex pattern, and then deletes any number of characters, to an unacceptable number, the regex pattern will still pass.</p>
  
  <p>How come this is happening, I mean onChange, should also check for deletions, and then the handler would validate again?</p>
  
  <p>EDIT:</p>
  
  <p>after comments, saying It's the regex pattern that is the problem i tried, using some console logs, to find the value of the current state, when It's validated</p>
  
  <pre><code>usernameValidator = (username) =&gt;{
  var usernameRegex = /^[a-zA-Z0-9]+([a-zA-Z0-9](_|-| )[a-zA-Z0-9])*[a-zA-Z0-9]+$/;
  if(usernameRegex.test(username)){
    this.setState({
      isUsernameCorrect: true
    }, console.log('correct'))
  }else if(!usernameRegex.test(username)){
    this.setState({
      isUsernameCorrect: false
    }, console.log('not correct'))
  }
    console.log(this.state.isUsernameCorrect)
    console.log(username)
  }
  </code></pre>
  
  <p>it always logs, the username, before the next key is typed so for example if the given username is <code>DDD</code>
  the passed in value will be <code>DD</code> because it gives in the username before the value is changed</p>