我想处理onChangeText
TextInput
React native
中的电话号码字段,
从this answer开始,我可以使用^08[0-9]{9,}$
模式,但是问题出在第一个数字上,正则表达式由于正则表达式模式上的08
而不会允许0,并且如果我添加0|08...
,则正则表达式允许0,但它允许任何第二个数字而不是08。
我的问题:强制正则表达式的第一个数字为0,第二个数字为8的最佳方法是什么?所以我得到08xxxxxxxxxx(当x是另一个数字0-9时)
我的当前代码是:
_onChangeHP(hp){
let reg = /^0|08[0-9]{9,}$/
if(reg.test(hp)){
this.setState({noHP:hp})
}
}
<TextInput
value={this.state.noHP}
placeholder={"Masukkan nomor handphone Anda"}
maxLength={13}
autoFocus={true}
keyboardType="numeric"
returnKeyType="next"
style={style.input}
onEndEditing={()=>this.inputEmail.focus()}
onChangeText={(text)=>this._onChangeHP(text)}
/>
您必须在正则表达式中使用groups。
您的问题的解决方案:/^(0|08|08[0-9]{1,9})$/
说明:捕获是0
还是08
或08x
或08xx
或08xxx
或08xxxx
...最多为08xxxxxxxxx
(即最多9个x,并且x可以是单个整数)数字)。