java 在android中检查有效的手机号码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16556997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking for valid mobile number in android
提问by dolphinately
I am currently making a registration for an application in android. I want to trap invalid mobile numbers entered in the EditText box. Once I click the submit button, the app will check if the mobile number entered is valid.
我目前正在为 android 中的应用程序进行注册。我想捕获在 EditText 框中输入的无效手机号码。单击提交按钮后,应用程序将检查输入的手机号码是否有效。
All valid number should start with "639"
. My question is how am I going to read the first three digits that the user entered? For example, the user enters 639158716271
, this a valid number. While 197837281919
is invalid.
所有有效数字都应以"639"
. 我的问题是如何读取用户输入的前三位数字?例如,用户输入639158716271
,这是一个有效数字。虽然197837281919
无效。
Can anyone suggest how to accomplish this?
谁能建议如何做到这一点?
Thanks in advance!
提前致谢!
回答by Shobhit Puri
Method 1:
方法一:
Get an instance of the EditText:
获取 EditText 的一个实例:
EditText myEdit = (EditText) findViewById(R.id.edittext1);
Then get the string that is currently being displayed:
然后获取当前正在显示的字符串:
String phoneNumber = myEdit.getText().toString();
If its only initial number that you want to match, then you can just compare as follows:
如果您只想匹配它的唯一初始数字,那么您可以进行如下比较:
String initialPart = phoneNumber.substring(0, 4);
//Get 1st three characters and then compare it with 639
boolean valid = initialPart.equals("639");
Then you can continue making other comparisons. However this method is prone to some mistakes and you might miss some corner case. So I suggest to go for method 2:
然后您可以继续进行其他比较。然而,这种方法容易出现一些错误,你可能会错过一些极端情况。所以我建议采用方法2:
Method:2
方法:2
However one another very good way is to use Google's libphonenumberlibrary. The documentation says:
然而,另一种非常好的方法是使用 Google 的libphonenumber库。文档说:
It is for parsing, formatting, storing and validating international phone numbers. The Java version is optimized for running on smartphone.
It is for parsing, formatting, storing and validating international phone numbers. The Java version is optimized for running on smartphone.
I have used it for verifying phone numbers. It is very easy to use and you don't need to take care of the corner cases. It takes into account your country/location and all sorts of formats that the user may enter. It checks if the number is valid for that region. It also takes care of all possible valid format that user may enter like:
"+xx(xx)xxxx-xxxx", "+x.xxx.xxx.xxx","+1(111)235-READ" ,"+1/234/567/8901", "+1-234-567-8901 x1234"
( here x is number).
我用它来验证电话号码。它非常易于使用,您无需处理极端情况。它考虑了您的国家/地区和用户可能输入的各种格式。它检查该号码是否对该地区有效。它还处理用户可能输入的所有可能的有效格式,如:(
"+xx(xx)xxxx-xxxx", "+x.xxx.xxx.xxx","+1(111)235-READ" ,"+1/234/567/8901", "+1-234-567-8901 x1234"
这里 x 是数字)。
Here is a sample usage of how to validate it:
以下是如何验证它的示例用法:
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
P.S: "CH"
is the country code for Switzerland. You can enter your country code based on your need. They are given here. Hope it helps.
PS:"CH"
是瑞士的国家代码。您可以根据需要输入您的国家/地区代码。它们在这里给出。希望能帮助到你。
回答by Steve P.
//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
matches()
ensures that the entire string cooresponds (exactly) to the regular expression that it takes. 639[0-9]{9}
says that the string must start off with 639 and then be followed by exactly 9 digits (0-9). If you wanted to match "639"
followed by 7 to 9 numbers, for example, you would use: 639[0-9]{7,9}
. Regular expressions: http://docs.oracle.com/javase/tutorial/essential/regex/
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/
回答by prvn
You can use the startsWith
method in your string object:
您可以startsWith
在字符串对象中使用该方法:
String num = "639158716271"
if (num.startsWith("639") && num.length() == 12)
// valid
else
// invaid
回答by Krauxe
Edit: This is a longer solution. Regex is the way to go for shorter code if all you really need is to verify the number as Steve pointed out.
编辑:这是一个更长的解决方案。如果您真正需要的是像史蒂夫指出的那样验证数字,那么正则表达式是缩短代码的方法。
===
===
First, restrict your EditText to accept only numbers, then you can use the following to verify the validity of the number.
首先,将您的 EditText 限制为仅接受数字,然后您可以使用以下内容来验证数字的有效性。
public static final int NUMBER_LENGTH = 9; // This will be used for validation
/**
* Returns the prefix of a phone number
*/
public String getNumberPrefix(String number) {
if (number != null) {
if (number.length() > NUMBER_LENGTH) {
return number.substring(0, number.length() - NUMBER_LENGTH);
}
}
return "";
}
/**
* Checks if a phone number is valid based on length and prefix
*/
public boolean isValidNumber(String number, String prefix) {
if (prefix == null) {
prefix = "";
}
if (number != null) {
if (number.length() > 0) {
if ((number.length() == NUMBER_LENGTH + prefix.length()) && (getNumberPrefix(number).equals(prefix))) {
return true;
}
}
}
return false;
}
So in your case, you could set a constant number length:
所以在你的情况下,你可以设置一个恒定的数字长度:
Some examples to use the method:
使用该方法的一些示例:
isValidNumber("639158716271", "639"); // This will return true
isValidNumber("631111111111", "639"); // This will return false
isValidNumber("6391587", "639"); // This will return false
isValidNumber("123456789000", "639"); // This will return false
回答by Parag Ghetiya
<EditText
android:id="@+id/EditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:maxLength="12"
/>
int number = Intiger.ParseInt(EditText.getText.toString());
if(number.startsWith("639")&& number.length == 12)
{
//valid
}
else
{
//invalid
}