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
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
.
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}$
To validate phone numbers for a specific region in Android, use libPhoneNumber from Google, and the following code as an example:
public boolean isPhoneNumberValid(String phoneNumber, String countryCode) {
// NOTE: This should probably be a member variable.
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
PhoneNumber numberProto = phoneUtil.parse(phoneNumber, countryCode);
return phoneUtil.isValidNumber(numberProto);
} catch (NumberParseException e) {
System.err.println("NumberParseException was thrown: " + e.toString());
}
return false;
}
You can use android's inbuilt Patterns
:
public boolean validCellPhone(String number) {
return android.util.Patterns.PHONE.matcher(number).matches();
}
This pattern is intended for searching for things that look like they might be phone numbers in arbitrary text, not for validating whether something is in fact a phone number. It will miss many things that are legitimate phone numbers.
The pattern matches the following:
- Optionally, a + sign followed immediately by one or more digits. Spaces, dots, or dashes may follow.
- Optionally, sets of digits in parentheses, separated by spaces, dots, or dashes.
- A string starting and ending with a digit, containing digits, spaces, dots, and/or dashes.
you can also check validation of phone number as
/**
* Validation of Phone Number
*/
public final static boolean isValidPhoneNumber(CharSequence target) {
if (target == null || target.length() < 6 || target.length() > 13) {
return false;
} else {
return android.util.Patterns.PHONE.matcher(target).matches();
}
}
^\+?\(?[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
You can use PhoneNumberUtils
if your phone format is one of the described formats. If none of the utility function match your needs, use regular experssions.
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();
}
}
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();
}
val UserMobile = findViewById<edittext>(R.id.UserMobile)
val msgUserMobile: String = UserMobile.text.toString()
fun String.isMobileValid(): Boolean {
// 11 digit number start with 011 or 010 or 015 or 012
// then [0-9]{8} any numbers from 0 to 9 with length 8 numbers
if(Pattern.matches("(011|012|010|015)[0-9]{8}", msgUserMobile)) {
return true
}
return false
}
if(msgUserMobile.trim().length==11&& msgUserMobile.isMobileValid())
{//pass}
else
{//not valid}
^\+201[0|1|2|5][0-9]{8}
this regex matches Egyptian mobile numbers
Here is how you can do it succinctly in Kotlin:
fun String.isPhoneNumber() =
length in 4..10 && all { it.isDigit() }
I got best solution for international phone number validation and selecting country code below library is justified me Best library for all custom UI and functionality CountryCodePickerProject
What about this method:
private static boolean validatePhoneNumber(String phoneNumber) {
// validate phone numbers of format "1234567890"
if (phoneNumber.matches("\\d{10}"))
return true;
// validating phone number with -, . or spaces
else if (phoneNumber.matches("\\d{3}[-\\.\\s]\\d{3}[-\\.\\s]\\d{4}"))
return true;
// validating phone number with extension length from 3 to 5
else if (phoneNumber.matches("\\d{3}-\\d{3}-\\d{4}\\s(x|(ext))\\d{3,5}"))
return true;
// validating phone number where area code is in braces ()
else if (phoneNumber.matches("\\(\\d{3}\\)-\\d{3}-\\d{4}"))
return true;
// Validation for India numbers
else if (phoneNumber.matches("\\d{4}[-\\.\\s]\\d{3}[-\\.\\s]\\d{3}"))
return true;
else if (phoneNumber.matches("\\(\\d{5}\\)-\\d{3}-\\d{3}"))
return true;
else if (phoneNumber.matches("\\(\\d{4}\\)-\\d{3}-\\d{3}"))
return true;
// return false if nothing matches the input
else
return false;
}
System.out.println("Validation for 1234567890 : " + validatePhoneNumber("1234567890"));
System.out.println("Validation for 1234 567 890 : " + validatePhoneNumber("1234 567 890"));
System.out.println("Validation for 123 456 7890 : " + validatePhoneNumber("123 456 7890"));
System.out.println("Validation for 123-567-8905 : " + validatePhoneNumber("123-567-8905"));
System.out.println("Validation for 9866767545 : " + validatePhoneNumber("9866767545"));
System.out.println("Validation for 123-456-7890 ext9876 : " + validatePhoneNumber("123-456-7890 ext9876"));
And the outputs:
Validation for 1234567890 : true
Validation for 1234 567 890 : true
Validation for 123 456 7890 : true
Validation for 123-567-8905 : true
Validation for 9866767545 : true
Validation for 123-456-7890 ext9876 : true
For more info please refer to this link.
Try this function it should work.
fun isValidPhone(phone: String): Boolean =
phone.trimmedLength() in (10..13) && Patterns.PHONE.matcher(phone).matches()
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.
精彩评论