Search code examples
reactjsfunctionkeypressonkeypress

React keypress input


I'm trying to prevent some characters from being entered, but for some reason the ban does not happen. Where was I wrong?

render () {
    return <form>
        <input
            id="username"
            type="text"
            placeholder="Username"
            value={this.state.value}
            onKeyPress={this.pale_username.bind(this)}
        />
    </form>
}

and function

pale_username(key) {
    if((key.charCode < 48 || key.charCode > 57) //numbers
        && (key.charCode < 65 || key.charCode > 90) // AB
        && (key.charCode < 97 || key.charCode > 122) // ab
        && (key.charCode !== 36) // $
        && (key.charCode !== 38) // &
        && (key.charCode < 40 || key.charCode > 41) // ()
        && (key.charCode < 45 || key.charCode > 46) // -.
        && (key.charCode !== 95) // _
        && (key.charCode !== 127) // del
        && (key.charCode !== 8) // BackSpace
        && (key.charCode !== 46))
        return false;
}

Solution

  • I would handle the character 'ban' in an onChange handler. One reason is, what happens if someone copy and pastes something into your input? Preventing the input in a keyboard event handler will not work.

    I would try something like this:

    handleChange(e) {
      // Use whatever regex you need.
      const filteredInput = e.target.value.replace(/[abAB$&()-_.*]|\d+/g, '');
      this.setState(value: filteredInput)
    }
    

    And then use it in your input.

    <input
      id="username"
      type="text"
      placeholder="Username"
      value={this.state.value}
      onChange={this.handleChange.bind(this)}
    />