Enter keystroke

I am trying to prevent some characters from being entered, but for some reason the ban does not occur. 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; } 
+5
source share
2 answers

I would handle the ban symbol in the onChange handler. One reason: what happens if someone copies and pastes something into your input? Preventing input in the 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 to enter.

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

onKeyDown detects charCode and onKeyPress detects keyCode . Try changing it to onKeyDown

0
source

Source: https://habr.com/ru/post/1274403/


All Articles