简体   繁体   English

页面加载后,输入类型验证第一次不起作用

[英]Input type validations are not working for the very first time after page loads

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函数:

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) . 这将删除this.onlyAlpha.bind(this)的用法。

Also, I think you should pass the function to the onChange listener like so: 另外,我认为您应该将函数传递给onChange侦听器,如下所示:

<input type="text" value={this.state.NomName} id="nominee" class="form-control"
    onChange={this.onlyAlpha} autoComplete="off"
    maxLength="100"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM