I have a text box, in that I wants to allow only alphabets.
Below is my code :
state ={
NomName: '',
}
onlyAlpha(e) {
var regex = /^[a-zA-Z ]*$/;
if(e.target.value === '' || regex.test(e.target.value)) {
this.setState({NomName:e.target.value})
}
}
render = () => {
return (
<label for="nominee">Nominee name</label>
<input type="text" value={this.state.NomName} id="nominee" class="form-control"
onChange={this.onlyAlpha.bind(this)} autoComplete="off"
maxLength="100"/>
)}
The input validations are not working (I am able to enter Numbers) at very first time after page loads. But once you cleared the field and try to re-enter the value it won't takes numbers (It works).
How can I make it run at each and every time.?
Please let me know if I am doing anything wrong.
I suggest you start using fat arrow functions. Make the onlyAlpha
function like so:
onlyAlpha = (e) => {
var regex = /^[a-zA-Z ]*$/;
if(e.target.value === '' || regex.test(e.target.value)) {
this.setState({NomName:e.target.value})
}
}
This would remove the usage of this.onlyAlpha.bind(this)
.
Also, I think you should pass the function to the onChange
listener like so:
<input type="text" value={this.state.NomName} id="nominee" class="form-control"
onChange={this.onlyAlpha} autoComplete="off"
maxLength="100"/>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.