5

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;
}
woe-dev.
  • 933
  • 1
  • 7
  • 12

2 Answers2

1

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)}
/>
Max
  • 1,517
  • 9
  • 16
  • Thank you! Can you still tell me how not to list the locked ones, but to allow only some?) – woe-dev. Dec 31 '17 at 01:27
  • I'll just put '^' in the beginning – woe-dev. Dec 31 '17 at 01:34
  • Edited the regex. Also, I just looked at your question again. if you want to prevent backspace and delete, you should check if `event.target.value` is shorter than `this.state.value` before calling `setState`. – Max Dec 31 '17 at 01:36
  • Thank you, but I do not think I will need this, because the user should be able to edit)) – woe-dev. Dec 31 '17 at 01:44
0

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

Kenry Sanchez
  • 1,703
  • 2
  • 18
  • 24
  • onKeyDown does not work for me, because I'm looking for charCode characters – woe-dev. Dec 31 '17 at 00:24
  • look at this. it's a similar question with a similar answer!! i hope it can help you https://stackoverflow.com/questions/27827234/keypress-event-handling-in-reactjs – Kenry Sanchez Dec 31 '17 at 00:30
  • I tried it. Problem still exists. I can still type characters like '#' – woe-dev. Dec 31 '17 at 00:43
  • Thanks for trying) I'm very glad that you tried to help.) The decision above worked. Perhaps you too need help) – woe-dev. Dec 31 '17 at 01:35