Phone number validation Android

2019-01-10 16:45发布

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 "+"\n"+" 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

12条回答
何必那么认真
2楼-- · 2019-01-10 17:24

Here is how you can do it succinctly in Kotlin:

fun String.isPhoneNumber() =
            length in 4..10 && all { it.isDigit() }
查看更多
你好瞎i
3楼-- · 2019-01-10 17:27

You can use this library . All you need do is pass the Country and phonenumber you want to validate.

查看更多
乱世女痞
4楼-- · 2019-01-10 17:27
^\+?\(?[0-9]{1,3}\)? ?-?[0-9]{1,3} ?-?[0-9]{3,5} ?-?[0-9]{4}( ?-?[0-9]{3})?

Check your cases here: https://regex101.com/r/DuYT9f/1

查看更多
Anthone
5楼-- · 2019-01-10 17:31
 String validNumber = "^[+]?[0-9]{8,15}$";

            if (number.matches(validNumber)) {
                Uri call = Uri.parse("tel:" + number);
                Intent intent = new Intent(Intent.ACTION_DIAL, call);
                if (intent.resolveActivity(getPackageManager()) != null) {
                    startActivity(intent);
                }
                return;
            } else {
                Toast.makeText(EditorActivity.this, "no phone number available", Toast.LENGTH_SHORT).show();
            }
查看更多
小情绪 Triste *
6楼-- · 2019-01-10 17:35

You shouldn't be using Regular Expressions when validating phone numbers. Check out this JSON API - numverify.com - it's free for a nunver if calls a month and capable of checking any phone number. Plus, each request comes with location, line type and carrier information.

查看更多
看我几分像从前
7楼-- · 2019-01-10 17:41

We can use pattern to validate it.

android.util.Patterns.PHONE

public class GeneralUtils {

    private static boolean isValidPhoneNumber(String phoneNumber) {
        return !TextUtils.isEmpty(phoneNumber) && android.util.Patterns.PHONE.matcher(phoneNumber).matches();
    }

}
查看更多
登录 后发表回答