处理onChangeText中的正则表达式电话号码的最佳方法react native

问题描述 投票:0回答:1

我想处理onChangeTextTextInputReact 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)}
  />
javascript regex react-native textinput
1个回答
0
投票

您必须在正则表达式中使用groups

您的问题的解决方案:/^(0|08|08[0-9]{1,9})$/

说明:捕获是0还是0808x08xx08xxx08xxxx ...最多为08xxxxxxxxx(即最多9个x,并且x可以是单个整数)数字)。

© www.soinside.com 2019 - 2024. All rights reserved.