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?

4

3 に答える 3

2

入力に ​​EditText を使用し、次の xml 属性を指定します。

android:inputType="phone"

ユーザーは無効な文字を中に入れることはできません。

01 のパターンでは、最初の 2 文字が「01」であるかどうかを確認するだけです。

if( phoneNumer.charAt(0)=='0'&&phoneNumber.charAt(1)=='1')
于 2012-05-16T10:38:05.673 に答える
0

この方法が役立つ場合があります。文字列に数値以外の文字が含まれている場合、このメソッドは false を返します。

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;
    }
于 2012-05-16T10:37:40.307 に答える
0

電話番号の検証は非常に複雑になる可能性がありますが、これについてはこのスレッドで以前に議論されているようです。

于 2012-05-16T10:36:50.037 に答える