woe-dev.
woe-dev.

Reputation: 993

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

Upvotes: 5

Views: 5949

Answers (2)

Max
Max

Reputation: 1567

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

Upvotes: 1

Kenry Sanchez
Kenry Sanchez

Reputation: 1743

onKeyDown detects charCode and onKeyPress detects keyCode. Try change it for onKeyDown

Upvotes: 0

Related Questions