电话号码验证机器人 [英] Phone number validation Android
问题描述
如何查询电话号码是有效或不。含有高达长度13和包括字符+前方。
How to check phone number is valid or not. containing upto length 13 and including character + infront.
如何做到这一点?
我尝试这样做:
String regexStr = "^[0-9]$";
String number=entered_number.getText().toString();
if(entered_number.getText().toString().length()<10 || number.length()>13 || number.matches(regexStr)==false ) {
Toast.makeText(MyDialog.this,"Please enter "+"\n"+" valid phone number",Toast.LENGTH_SHORT).show();
// am_checked=0;
}`
和也试过这样的:
public boolean isValidPhoneNumber(String number)
{
for (char c : number.toCharArray())
{
if (!VALID_CHARS.contains(c))
{
return false;
}
}
// All characters were valid
return true;
}
这两个不工作。
Both not working.
输入类型: +号被接受,从0到9的数字和长度B / W 10-13和SHLD不Accpet头其他字符
推荐答案
给你指定的规则:
高达长度13和包括字符+前方。
upto length 13 and including character + infront.
(也结合了最小长度10在code)
(and also incorporating the min length of 10 in your code)
你会希望有一个正则表达式是这样的:
You're going to want a regex that looks like this:
^\+[0-9]{10,13}$
通过最小和最大长度EN codeD中的正则表达式,你可以将这些条件从如果()
块。
With the min and max lengths encoded in the regex, you can drop those conditions from your if()
block.
题外话:我建议范围为10 - 13太限制了一个国际电话号码字段;你几乎一定会找到有效的数字是两个比这更长和更短。我建议了一系列的8 - 20是安全的。
Off topic: I'd suggest that a range of 10 - 13 is too limiting for an international phone number field; you're almost certain to find valid numbers that are both longer and shorter than this. I'd suggest a range of 8 - 20 to be safe.
OP指出上述正则表达式不因转义序列的工作。不知道为什么,但更好的方法是:
OP states the above regex doesn't work due to the escape sequence. Not sure why, but an alternative would be:
^[+][0-9]{10,13}$
OP现在增加了 +
标志应该是可选的。在这种情况下,正则表达式需要经过一个问号 +
,所以上面的例子,现在是这样的:
OP now adds that the +
sign should be optional. In this case, the regex needs a question mark after the +
, so the example above would now look like this:
^[+]?[0-9]{10,13}$
这篇关于电话号码验证机器人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!