Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Kiểm tra số điện thoại hợp lệ bằng Regex trong Android

Mục tiêu

Validate định dạng số điện thoại nhập vào EditText sử dụng Regular Expression (Regex).

Các bước

Bước 1: Tạo project

Bước 2: Layout activity_main.xml

<LinearLayout ... android:gravity="center" android:orientation="vertical">
    <EditText android:id="@+id/enterNumber" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter phone number" />
    <TextView android:id="@+id/text" android:textSize="18sp" android:textAlignment="center" android:text="Validate" android:layout_width="match_parent" android:layout_height="wrap_content" />
</LinearLayout>

Bước 3: MainActivity.java

public class MainActivity extends AppCompatActivity {
    TextView btnValidate;
    EditText etPhone;
    // Regex hỗ trợ: +country code, dấu ngoặc, gạch ngang, khoảng trắng, extension
    private static final String PHONE_PATTERN = "^\\s*(?:\\+?(\\d{1,3}))?[-. (]*(\\d{3})[-. )]*(\\d{3})[-. ]*(\\d{4})(?: *x(\\d+))?\\s*$";
    private Pattern pattern = Pattern.compile(PHONE_PATTERN);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnValidate = findViewById(R.id.text);
        etPhone = findViewById(R.id.enterNumber);

        btnValidate.setOnClickListener(v -> {
            String input = etPhone.getText().toString().trim();
            if (input.isEmpty()) {
                Toast.makeText(this, "Please enter mobile number", Toast.LENGTH_LONG).show();
                return;
            }
            Matcher matcher = pattern.matcher(input);
            if (matcher.find()) {
                Toast.makeText(this, "MATCH - Valid phone", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "NO MATCH - Invalid format", Toast.LENGTH_LONG).show();
            }
        });
    }
}

Giải thích Regex:

^\\s*                     # Bỏ qua khoảng trắng đầu
(?:\\+?(\\d{1,3}))?        # Country code tùy chọn (+1, +84...)
[-. (]*                    # Các phân cách: -, ., (, space
(\\d{3})                   # 3 chữ số đầu (area code)
[-. )]*                    # Phân cách
(\\d{3})                   # 3 chữ số giữa
[-. ]*                     # Phân cách
(\\d{4})                   # 4 chữ số cuối
(?: *x(\\d+))?             # Extension tùy chọn (x123)
\\s*$                      # Bỏ qua khoảng trắng cuối

Kết quả

Nhập số hợp lệ (VD: +1 (555) 123-4567) → MATCH:

Kiểm tra số điện thoại hợp lệ bằng Regex trong Android

Nhập sai định dạng → NO MATCH:

Kiểm tra số điện thoại hợp lệ bằng Regex trong Android

Lưu ý

  • Regex trên phù hợp format US. VN cần điều chỉnh (10-11 số, bắt đầu 03, 05, 07, 08, 09...).
  • Regex VN đơn giản: ^(0[3|5|7|8|9])+([0-9]{8})\\b$.
  • Nên dùng thư viện libphonenumber (Google) cho validate quốc tế chuẩn xác.