手机号码验证安卓
如何检查电话号码是否有效?最大长度为13(包括前面的字符+
).
How do I check if a phone number is valid or not? It is up to length 13 (including character +
in front).
我该怎么做?
我试过了:
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 "+"
"+" 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;
}
两者都不起作用.
输入类型:+号被接受,0-9个数字,长度b/w 10-13,不能接受其他字符
鉴于您指定的规则:
长度不超过 13,包括字符 + 前面.
upto length 13 and including character + infront.
(并在您的代码中加入最小长度 10)
(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}$
使用正则表达式中编码的最小和最大长度,您可以从 if()
块中删除这些条件.
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}$