IT/Android
[Android] 전화번호 하이픈(-) 표시 및 포맷 체크하기
Kanzler
2016. 8. 2. 11:47
전화번호를 입력 하거나 가져올때 표시에 하이픈(-)이 들어가도록 표시 해주는게 좋습니다.
'0212345678' 보다는 02-1234-5678'으로 표현 하는것이 훨씬 가독성이 있고 사용자에게 익숙 하기 때문입니다.
Android에서는 이와 같이 입력된 String에 대해서 자동으로 '-'를 처리 해주는 메소드를 제공 해주고 있습니다.
//전화번호 포맷 변환 yourTextView.setText(PhoneNumberUtils.formatNumber(yourStringPhone, Locale.getDefault().getCountry())); //
지역 코드값을 넣어주면 입력된 String을 지역코드에 맞게 변환해줍니다.
전화 번호 포맷 체크 하기
앞에 코드에서 리턴된 전화번호('-' 포함된 전화번호)가 실제 국내에서 사용 중인 전화번호에 맞는 포맷인지 체크 하는 소스입니다.
public static boolean isValidCellPhoneNumber(String cellphoneNumber) { boolean returnValue = false; try { String regex = "^\\s*(010|011|016|017|018|019)(-|\\)|\\s)*(\\d{3,4})(-|\\s)*(\\d{4})\\s*$"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(cellphoneNumber); if (m.matches()) { returnValue = true; } if (returnValue && cellphoneNumber != null && cellphoneNumber.length() > 0 && cellphoneNumber.startsWith("010")) { cellphoneNumber = cellphoneNumber.replace("-", ""); if (cellphoneNumber.length() != 11) { returnValue = false; } } return returnValue; } catch (Exception e) { return false; } }