[英]how to validate user phone number in textinput?
I have a textinput
and i want to validate user input before it's showing on textinput
.我有一个
textinput
,我想在它显示在textinput
之前验证用户输入。
i have tried used regex to do this, but i have a problem with the following code:我曾尝试使用正则表达式来执行此操作,但我对以下代码有疑问:
_onChangeHP(hp){
console.log('hp', hp)
let reg = /^08[0-9]{9,}$/
if(reg.test(hp)){
this.setState({noHP:hp})
}
}
<TextInput
value={this.state.noHP}
maxLength={13}
placeholder={'08xxxxxxxxx'}
keyboardType="numeric"
onChangeText={(text)=>this._onChangeHP(text)}
/>
_onChangeHP()
function checked one by one, so regex pattern
never pass true in if statement
, _onChangeHP()
function 一一检查,所以regex pattern
永远不会在if statement
中传递 true ,
is there a way to validate user input?有没有办法验证用户输入?
My Expected result is setState
when user value first string is 0
and 2nd string is 8
and the rest is numeric only,当用户值第一个字符串为
0
且第二个字符串为8
并且 rest 仅为数字时,我的预期结果是setState
,
you can use pattern function where number can be put in conditional.您可以使用模式 function ,其中数字可以有条件地输入。
<input maxLength={13} placeholder='08xxxxxxxxx' keyboardType="numeric"
pattern="[0][8][0-9]{11}" />
you can't do it with only one regex你不能只用一个正则表达式
_onChangeHP('08') _onChangeHP('01') _onChangeHP('08222222') function _onChangeHP(hp){ let regStartsWith = new RegExp('^08', 'i'); let regAfter = /^\d+$/; if(regStartsWith.test(hp)){ // this will check if starts with 08 if(regAfter.test(hp.substring(2))){ console.log(true) // this will check if hp has number after 08 return true; } else{ console.log(false); return false; } } else{ console.log(false); return false; } }
You'll have to use groups in regular expressions.您必须在正则表达式中使用组。
The solution to your problem: /^(0|08|08[0-9]{1,9})$/
您的问题的解决方案:
/^(0|08|08[0-9]{1,9})$/
Explanation: Capture if it's a 0
or 08
or 08x
or 08xx
or 08xxx
or 08xxxx
... upto 08xxxxxxxxx
( ie upto 9 x's, and x can be any single digit number ).说明:捕获它是否是
0
或08
或08x
或08xx
或08xxx
或08xxxx
... 08xxxxxxxxx
(即最多 9 个 x,x 可以是任何一位数)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.