Javascript 确保输入值是reactjs中的字母字符串
我正在开发一个reactjs应用程序,我希望我的用户只能在输入字段中输入字母。 这是我的密码Javascript 确保输入值是reactjs中的字母字符串,javascript,reactjs,validation,restrict,Javascript,Reactjs,Validation,Restrict,我正在开发一个reactjs应用程序,我希望我的用户只能在输入字段中输入字母。 这是我的密码 <input value= {this.state.val} onChange = {this.handleVal}/> handleVal = (e)=>{ this.setState({ val:e.target.value }) } state = { val:'' } 扶手=(e)=>{ 这是我的国家({ val:e.targ
<input value= {this.state.val} onChange = {this.handleVal}/>
handleVal = (e)=>{
this.setState({
val:e.target.value
})
}
state = {
val:''
}
扶手=(e)=>{
这是我的国家({
val:e.target.value
})
}
状态={
val:'
}
我的组件有很多代码,但我只输入了相关的代码。
提前感谢。您可以使用正则表达式测试,并且仅当输入状态通过onChange处理程序上的测试时才更新输入状态
/^[a-zA-Z]*$/
handleVal = (e) => {
const value = e.target.value;
const regMatch = /^[a-zA-Z]*$/.test(value);
if (regMatch) {
this.setState({
val: value
})
}
};
onChange处理程序中的用法
/^[a-zA-Z]*$/
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
})
}
onKeyPress=(事件)=>{
如果((event.charCode>64&&event.charCode<91)| |(event.charCode>96&&
event.charCode<123){
返回true;
}
返回false;
}
onChange=(e)=>{
log('''''''''''''''''''''''''''''''''''''''''''e.target.value');
这是我的国家({
价值:即目标价值
})
}