4

I have a UI where user enters the cell number and the number is stored in a string variable and then its stored into the database.

I want to validate the string to check whether the string does not contain any characters.

How do I do that?

Below is the string code.

EditText editText3 = (EditText) this.findViewById(R.id.editText2);
setNum = editText3.getText().toString(); //setNum would contain something link 8081124589
tech_learner
  • 725
  • 11
  • 21
  • 31
  • 1
    By definition, all strings contain *characters* except null or empty strings. Do you mean *letters*? Or perhaps special characters such as `-.() /`? Or any character that isn't a numeral? – Justin Morgan - On strike May 12 '11 at 01:06

6 Answers6

28

To validate a string, use

if (setNum.matches(regexStr))

where regexStr can be:

//matches numbers only
String regexStr = "^[0-9]*$"

//matches 10-digit numbers only
String regexStr = "^[0-9]{10}$"

//matches numbers and dashes, any order really.
String regexStr = "^[0-9\\-]*$"

//matches 9999999999, 1-999-999-9999 and 999-999-9999
String regexStr = "^(1\\-)?[0-9]{3}\\-?[0-9]{3}\\-?[0-9]{4}$"

There's a very long regex to validate phones in the US (7 to 10 digits, extensions allowed, etc.). The source is from this answer: A comprehensive regex for phone number validation

String regexStr = "^(?:(?:\\+?1\\s*(?:[.-]\\s*)?)?(?:\\(\\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\\s*\\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\\s*(?:[.-]\\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\\s*(?:[.-]\\s*)?([0-9]{4})(?:\\s*(?:#|x\\.?|ext\\.?|extension)\\s*(\\d+))?$"
Community
  • 1
  • 1
Aleadam
  • 40,203
  • 9
  • 86
  • 108
  • Looks decent to me, although you might want to allow for parentheses, dots, and spaces in your shorter patterns. I myself usually write U.S. phone numbers as `(234) 567-8900`. The long regex is pretty scary and maybe a little *too* restrictive, but it does look very comprehensive to me. You have some unescaped backslashes toward the end, though. – Justin Morgan - On strike May 12 '11 at 01:19
  • One thing I'd watch out for is international numbers, which can be several different formats and lengths. If you can find it, you might consider looking up the regex Skype uses to turn numbers into hyperlinks. – Justin Morgan - On strike May 12 '11 at 01:23
  • @Justin thanks for looking at it. Escaping the backslashes was my only addition to the "scary" regex and it was incomplete :/ I'll wait for the OP reply to see if he needs any other pattern. – Aleadam May 12 '11 at 01:59
11

For API level 8 or above :

public static final boolean isValidPhoneNumber(CharSequence target) {
    if (target == null || TextUtils.isEmpty(target)) {
        return false;
    } else {
        return android.util.Patterns.PHONE.matcher(target).matches();
    }
}
Vaibhav Jani
  • 12,428
  • 10
  • 61
  • 73
  • 3
    This is the best solution (or using PhoneNumberUtils.isGlobalPhoneNumber). One minor tweak, checking if target == null is not necessary since TextUtils.isEmpty handles that check for you. – ToddH Jun 19 '14 at 15:07
  • 1
    Perfect one !! Helped me a lot – Jigar Oct 07 '14 at 07:54
  • 1
    read the source code's comments: /** * 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. * Therefore, it's not the best solution~ – shanwu May 16 '16 at 09:52
  • @shanwu This pattern can be used if you want to allow multiple style phone numbers in input field like EditText. You are right as this is not a validation for exact phone number that can be called(dialled) without any modification. – Vaibhav Jani May 16 '16 at 10:06
1

I like to use PhoneNumberUtils. Specifically - formatNumber(String num, String defaultCountryIso). formatNumber(); will return null if it is an invalid number after attempting to format it. Otherwise, it will return the formatted string.

Example:

 EditText editText3 = (EditText) this.findViewById(R.id.editText2);
 String setNum;

 if(!TextUtils.isEmpty(editText3.getText()){
      setNum = editText3.getText.toString();

      /* format with PhoneNumberUtils */
      TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
      String mCountryCode = telephonyManager.getNetworkCountryIso();

      // I like to check for sdk cause less than 21 won't support default country code
      if (android.os.Build.VERSION.SDK_INT >= 21) {
          setNum = PhoneNumberUtils.formatNumber(phoneNumber, mCountryCode);
       } else {
          // this one is deprecated
          setNum = PhoneNumberUtils.formatNumber(phoneNumber);
       }

      // if setNum is not null, you now have a valid formatted number
      if(setNum != null){
         return true;
      } else {
         editText3.setError("Invalid phone number");
         Log.d(TAG, "Invalid phone number: " + setNum); 
         return false;
      }
 } else {
    return false;
 }

Also, you may need permission for the TelephonyManager [not too sure? need link]. If so, add this to the manifest:

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

Chad Bingham
  • 32,650
  • 19
  • 86
  • 115
1

if you simply want to test if its a number you could do try{Integer.parseInt(setNum); keep going} catch (Exception e) {oops not a number}

or Double.parseDouble(setNum); depending on what kind of number you are expecting.

or you could remove whitespace first then do the above.

or you could use a regex but thats likely overkill.

but perhaps you should be limiting the characters allowed in the edittext in the firstplace. in the xml file you could add the property android:digits="0123456789-()" for example.

you could also try to pre-populate the phone number if you are trying to get the phone number of the device the app is installed on:

TelephonyManager tMgr =(TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
  mPhoneNumber = tMgr.getLine1Number();

and uses-permission android:name="android.permission.READ_PHONE_STATE".

note this doesn't always work (see Programmatically obtain the phone number of the Android phone)

Community
  • 1
  • 1
jkhouw1
  • 7,320
  • 3
  • 32
  • 24
  • 1
    do you really think a regex string is overkill, compared to querying the TelephonyManager? – Aleadam May 11 '11 at 22:34
  • 1
    querying the telephymanager was actually just a thought in the event he was trying to get the number of the phone where his app is installed and pre-load it for his userbase. It actually wasn't directly related to number validation just giving him some ideas. I actually think the best idea is just limit the characters the user can input. – jkhouw1 May 12 '11 at 00:54
  • I think limiting the characters the user can input is definitely the best way to go, if it's available. – Justin Morgan - On strike May 12 '11 at 01:26
  • I agree on that. Limiting the input is the best way. I don't know if it can be limited in his app or if it will be part of a bigger string. – Aleadam May 12 '11 at 02:02
0

You can use a regex like one of the repliers already stated. To route the violation message to the component one can use the setError message;

TextView v = (TextView) view;
setError(message);

This is the standard technique marking a UI component having an error. It has been leveraged inside the BARACUS Framework for Android application in order to have declarative form validation in android.

Since the stuff is Apache 2 licensed, feel free to verbatim the code.

gorefest
  • 849
  • 8
  • 22
0

You can use a regex pattern to validate the phone number format.

Considering these facts about phone number format:-

  1. Country Code prefix starts with ‘+’ and has 1 to 3 digits
  2. Last part of the number, also known as subscriber number is 4 digits in all of the numbers
  3. Most of the countries have 10 digits phone number after excluding country code. A general observation is that all countries phone number falls somewhere between 8 to 11 digits after excluding country code.
String allCountryRegex = "^(\\+\\d{1,3}( )?)?((\\(\\d{1,3}\\))|\\d{1,3})[- .]?\\d{3,4}[- .]?\\d{4}$";

Let's break the regex and understand,

  • ^ start of expression
  • (\\+\\d{1,3}( )?)? is optional match of country code between 1 to 3 digits prefixed with '+' symbol, followed by space or no space.
  • ((\\(\\d{1,3}\\))|\\d{1,3} is mandatory group of 1 to 3 digits with or without parenthesis followed by hyphen, space or no space.
  • \\d{3,4}[- .]? is mandatory group of 3 or 4 digits followed by hyphen, space or no space
  • \\d{4} is mandatory group of last 4 digits
  • $ end of expression

This regex pattern matches most of the countries phone number format including these:-

        String Afghanistan      = "+93 30 539-0605";
        String Australia        = "+61 2 1255-3456";
        String China            = "+86 (20) 1255-3456";
        String Germany          = "+49 351 125-3456";
        String India            = "+91 9876543210";
        String Indonesia        = "+62 21 6539-0605";
        String Iran             = "+98 (515) 539-0605";
        String Italy            = "+39 06 5398-0605";
        String NewZealand       = "+64 3 539-0605";
        String Philippines      = "+63 35 539-0605";
        String Singapore        = "+65 6396 0605";
        String Thailand         = "+66 2 123 4567";
        String UK               = "+44 141 222-3344";
        String USA              = "+1 (212) 555-3456";
        String Vietnam          = "+84 35 539-0605";

Source:https://codingnconcepts.com/java/java-regex-for-phone-number/

Ashish Lahoti
  • 648
  • 6
  • 8