Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

Phone number validation Android

How do I check if a phone number is valid or not? It is up to length 13 (including character + in front).

How do I do that?

I tried this:

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;
}`

And I also tried this:

public boolean isValidPhoneNumber(String number)
{
     for (char c : number.toCharArray())
     {
         if (!VALID_CHARS.contains(c))
         {
            return false;
         }
     }
     // All characters were valid
     return true;
}

Both are not working.

Input type: + sign to be accepted and from 0-9 numbers and length b/w 10-13 and should not accept other characters

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use isGlobalPhoneNumber() method of PhoneNumberUtils to detect whether a number is valid phone number or not.

Example

System.out.println("....g1..."+PhoneNumberUtils.isGlobalPhoneNumber("+912012185234"));
System.out.println("....g2..."+PhoneNumberUtils.isGlobalPhoneNumber("120121852f4"));

The result of first print statement is true while the result of second is false because the second phone number contains f.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...