在android中检查有效的手机号码

dol*_*ely 0 java android

我目前正在注册android中的应用程序.我想要捕获在EditText框中输入的无效手机号码.点击提交按钮后,应用程序将检查输入的手机号码是否有效.

所有有效号码都应该以"639".我的问题是如何阅读用户输入的前三位数字?例如,用户输入639158716271此有效数字.虽然197837281919无效.

任何人都可以建议如何做到这一点?

提前致谢!

Ste*_* P. 5

     //Get the string from the edit text by:
     String number = yourEditText.getText().toString();

     if(number != null && number.matches("639[0-9]{9}"))
     //do what you need to do for valid input
     else
     //do what you need to do for invalid input
Run Code Online (Sandbox Code Playgroud)

matches()确保整个字符串 cooresponds (exactly) 到它所采用的正则表达式。639[0-9]{9}表示字符串必须以 639 开头,然后紧跟 9 位数字 (0-9)。例如,如果您想匹配"639"后跟 7 到 9 个数字,则可以使用:639[0-9]{7,9}。正则表达式:http : //docs.oracle.com/javase/tutorial/essential/regex/


Sho*_*uri 5

方法1:

获取EditText的实例:

EditText myEdit = (EditText) findViewById(R.id.edittext1);
Run Code Online (Sandbox Code Playgroud)

然后获取当前显示的字符串:

String phoneNumber = myEdit.getText().toString();
Run Code Online (Sandbox Code Playgroud)

如果它只是您想要匹配的初始数字,那么您可以按如下方式进行比较:

String initialPart = phoneNumber.substring(0, 4);  
//Get 1st three characters and then compare it with 639
boolean valid = initialPart.equals("639");
Run Code Online (Sandbox Code Playgroud)

然后你可以继续进行其他比较.然而,这种方法容易出错,你可能会错过一些极端情况.所以我建议采用方法2:

方法:2

然而,另一个非常好的方法是使用谷歌的libphonenumber.文件说:

It is for parsing, formatting, storing and validating international phone numbers. The Java version is optimized for running on smartphone.

我用它来验证电话号码.它非常易于使用,您无需处理角落情况.它会考虑您的国家/地区以及用户可能输入的各种格式.它检查该号码是否对该区域有效.它还会处理用户可能输入的所有可能的有效格式:( "+xx(xx)xxxx-xxxx", "+x.xxx.xxx.xxx","+1(111)235-READ" ,"+1/234/567/8901", "+1-234-567-8901 x1234"此处x为数字).

以下是如何验证它的示例用法:

PhoneNumber NumberProto = null;
String NumberStr = "639124463869"
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
  NumberProto = phoneUtil.parse(NumberStr, "CH"); 
} catch (NumberParseException e) {
  System.err.println("NumberParseException was thrown: " + e.toString());
}
boolean isValid = phoneUtil.isValidNumber(NumberProto); // returns true or false
Run Code Online (Sandbox Code Playgroud)

PS:"CH"是瑞士的国家代码.您可以根据需要输入国家/地区代码.他们在这里给出.希望能帮助到你.