确保输入值是reactjs中的字母字符串

问题描述

我正在开发reactjs应用程序,我希望我的用户必须在输入字段中仅输入字母。 这是我的代码。

<input value= {this.state.val} onChange = {this.handleVal}/>


handleVal = (e)=>{
      this.setState({
      val:e.target.value
      })
}


state = {
  val:''
}

我的组件有很多代码,但是我只输入了相关代码。 预先感谢。

解决方法

您可以使用正则表达式测试,并且仅在输入状态通过onChange处理程序上的测试时才更新输入状态

/^[a-zA-Z]*$/

onChange处理程序中的用法

  handleVal = (e) => {
    const value = e.target.value;
    const regMatch = /^[a-zA-Z]*$/.test(value);

    if (regMatch) {
        this.setState({
            val: value
        })
    }
  };
,

您可以使用onKeyPress方法,这样可以避免键入字母中的其他内容。

 <input placeholder="Enter Alphabets only" onKeyPress={this.onKeyPress} onChange={this.onChange} />

onKeyPress = (event) => {
   if((event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && 
     event.charCode < 123)){
        return true;
   }
      return false;
}

onChange =  (e) => {
  console.log('_________',e.target.value);
  this.setState({
      value: e.target.value
  })
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...