2
complete = (Button) findViewById(R.id.complete);
complete.setOnClickListener(new View.OnClickListener() {

        String validNumber = "";

    public void onClick(View v){

        validNumber = phoneNumber.getText().toString();

        if (!validNumber.equals("")){

                final String phoneNumPattern = "^(?=.*[0-9]){10,11}$";  
                Pattern pattern = Pattern.compile(phoneNumPattern);
                Matcher matcher = pattern.matcher(validNumber);     

                 if (matcher.matches() == true){
            Toast.makeText(PhoneNumActivity.this, "Success", Toast.LENGTH_SHORT).show();        
                 }
                 else{
            Toast.makeText(PhoneNumActivity.this, "Failed", Toast.LENGTH_SHORT).show();
                  }
        }
        else{
                 Toast.makeText(PhoneNumActivity.this, "Failed", Toast.LENGTH_SHORT).show();
        }
    }
 });

I am developing an security apps which user needs to enter a valid mobile phone number, I set the pattern above where user can only enter number with min 10 digit and max 11 digit. But it come out an error

java.util.regex.PatternSyntaxException: Syntax error in regexp pattern near index 13:

And one more question, can I set the pattern so that the first two digits of the mobile number is 01xxxxxxxxxx?

jmj
  • 237,923
  • 42
  • 401
  • 438
Android_Rookie
  • 509
  • 2
  • 10
  • 25
  • Apart from your regex issue, it is maybe worth checking that your pattern will work for any format of phone number accross countries. – assylias May 16 '12 at 10:32

3 Answers3

2

Use an EditText for the input and give it this xml attribute:

android:inputType="phone"

The user wont be able to put non valid characters inside.

For your pattern of 01 you just have to check if the first 2 chars are "01"

if( phoneNumer.charAt(0)=='0'&&phoneNumber.charAt(1)=='1')
Ostkontentitan
  • 6,930
  • 5
  • 53
  • 71
0

Phone number validation can be quite complex, but it looks like this has been discussed before in this thread.

Community
  • 1
  • 1
stuckless
  • 6,515
  • 2
  • 19
  • 27
0

This method may help you. This method returns false if string contains any non-numeric characters.

public static boolean abcd(String str)
    {
        int x;
        for(int j = 0 ; j < str.length() ; j++)
        {
            x = (int)str.charAt(j);
            if( x < 48 || x > 57 )
            return false;    
        }
        return true;
    }
Ravi Jain
  • 1,452
  • 2
  • 17
  • 41