Phone number validation Android

android, phone-number, validation

Solution

Given the rules you specified:

upto length 13 and including character + infront.

(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}$

With the min and max lengths encoded in the regex, you can drop those conditions from your `if()` block.

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.

[EDIT] 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}$

[EDIT 2] 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}$

Problem

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`

Original source

Related problems