정규 표현식을 사용한 전화번호 유효성 검사

2024-07-27

전화번호 형식

전화번호 형식은 국가마다 다릅니다. 하지만, 일반적으로 다음과 같은 요소들을 포함합니다.

  • 국가 코드: 국가를 식별하는 숫자입니다. 예를 들어, 미국은 +1, 한국은 +82입니다.
  • 지역 코드: 특정 지역을 식별하는 숫자입니다.
  • 전화번호: 개별 전화 번호를 식별하는 숫자입니다.

정규 표현식 작성

다음은 일반적인 전화번호 형식을 일치시키는 정규 표현식입니다.

^(\+[\d]{1,2})?(\d{2,5})[\d]{5,10}$
  • ^: 문자열의 시작을 나타냅니다.
  • (\+[\d]{1,2})?: 선택적으로 국가 코드를 허용합니다. 국가 코드는 "+"로 시작하고 1~2개의 숫자로 구성됩니다.
  • (\d{2,5}): 지역 코드를 나타냅니다. 지역 코드는 2~5개의 숫자로 구성됩니다.
  • [\d]{5,10}: 전화번호를 나타냅니다. 전화번호는 5~10개의 숫자로 구성됩니다.

프로그래밍 예시

다음은 Python에서 정규 표현식을 사용하여 전화번호 유효성을 검사하는 예시입니다.

import re

def is_valid_phone_number(phone_number):
  pattern = r"^(\+[\d]{1,2})?(\d{2,5})[\d]{5,10}$"
  return re.search(pattern, phone_number) is not None

phone_number = "+821234567890"

if is_valid_phone_number(phone_number):
  print(f"{phone_number}은 유효한 전화번호입니다.")
else:
  print(f"{phone_number}은 유효한 전화번호가 아닙니다.")

위 코드는 다음과 같은 결과를 출력합니다.

+821234567890은 유효한 전화번호입니다.

추가 고려 사항

  • 국가별 특정 요구 사항을 충족하도록 정규 표현식을 조정해야 할 수도 있습니다. 예를 들어, 특정 국가에서는 하이픈 또는 공백을 허용할 수 있습니다.
  • 국제 전화번호 형식을 처리하려면 정규 표현식을 더 복잡하게 만들어야 할 수도 있습니다.
  • 유효성 검사는 전화번호의 유일성을 보장하지 않는다는 점에 유의해야 합니다. 더 강력한 유효성 검사를 위해서는 전화번호 데이터베이스와 비교하는 것이 좋습니다.



예제 코드: 국가별 전화번호 유효성 검사

다음은 국가별 전화번호 유효성 검사를 위한 정규 표현식 및 코드 예시입니다.

미국 전화번호

미국 전화번호는 다음과 같은 형식을 따릅니다.

  • 국가 코드: +1
  • 지역 코드: 3자리 숫자
  • 전화번호: 7자리 숫자
pattern = r"^(\+1)?(\d{3})\d{7}$"
pattern = r"^(\+82)?(\d{2,3})\d{4,7}$"
pattern = r"^(\+81)?(\d{2,4})\d{3,7}$"

코드 예시

import re

def is_valid_phone_number(phone_number, country_code):
  if country_code == "US":
    pattern = r"^(\+1)?(\d{3})\d{7}$"
  elif country_code == "KR":
    pattern = r"^(\+82)?(\d{2,3})\d{4,7}$"
  elif country_code == "JP":
    pattern = r"^(\+81)?(\d{2,4})\d{3,7}$"
  else:
    return False

  return re.search(pattern, phone_number) is not None

phone_number = "+12123456789"
country_code = "US"

if is_valid_phone_number(phone_number, country_code):
  print(f"{phone_number}{country_code} 유효한 전화번호입니다.")
else:
  print(f"{phone_number}{country_code} 유효한 전화번호가 아닙니다.")
+12123456789은 US 유효한 전화번호입니다.
  • 더 많은 국가를 지원하려면 국가 코드 및 해당 국가의 전화번호 형식에 대한 정보를 추가해야 합니다.



정규 표현식 없이 전화번호 유효성 검사

문자열 길이 검사

가장 간단한 방법은 전화번호 문자열의 길이를 검사하는 것입니다. 대부분의 국가 전화번호는 특정 길이 범위를 가지고 있습니다. 예를 들어, 미국 전화번호는 일반적으로 10~11자리, 한국 전화번호는 9~11자리입니다.

def is_valid_phone_number_by_length(phone_number, country_code):
  if country_code == "US":
    return len(phone_number) == 10 or len(phone_number) == 11
  elif country_code == "KR":
    return len(phone_number) == 9 or len(phone_number) == 10 or len(phone_number) == 11
  elif country_code == "JP":
    return len(phone_number) == 10 or len(phone_number) == 11
  else:
    return False

숫자만 포함인지 검사

유효한 전화번호는 숫자만 포함되어야 합니다. 문자열의 모든 문자가 숫자인지 확인하는 함수를 사용할 수 있습니다.

def is_all_digits(phone_number):
  for char in phone_number:
    if not char.isdigit():
      return False
  return True

허용되지 않는 문자 검사

일부 국가에서는 특정 문자를 전화번호에 사용할 수 없습니다. 예를 들어, 미국에서는 하이픈(-) 또는 공백을 허용하지 않습니다. 해당 국가에서 허용되지 않는 문자가 포함되어 있지 않은지 확인하는 함수를 사용할 수 있습니다.

def is_valid_characters(phone_number, country_code):
  if country_code == "US":
    for char in phone_number:
      if char in ["-", " "]:
        return False
  # 다른 국가별 검사 코드 추가...
  return True

부분 문자열 검사

일부 국가에서는 특정 문자열로 시작하는 전화번호만 유효합니다. 예를 들어, 한국에서는 02 또는 05로 시작하는 전화번호만 유효합니다. 해당 국가의 유효한 접두사로 시작하는지 확인하는 함수를 사용할 수 있습니다.

def is_valid_prefix(phone_number, country_code):
  if country_code == "KR":
    if not phone_number.startswith("02") and not phone_number.startswith("05"):
      return False
  # 다른 국가별 검사 코드 추가...
  return True

통합

위에서 설명한 여러 방법을 결합하여 전화번호 유효성 검사를 수행할 수 있습니다.

def is_valid_phone_number(phone_number, country_code):
  if not is_valid_phone_number_by_length(phone_number, country_code):
    return False
  if not is_all_digits(phone_number):
    return False
  if not is_valid_characters(phone_number, country_code):
    return False
  if not is_valid_prefix(phone_number, country_code):
    return False
  return True

단점

  • 국가별 요구 사항을 모두 충족하기 어려울 수 있습니다.
  • 오류 가능성이 높습니다.
  • 정규 표현식을 사용하는 방법보다 코드가 더 복잡하고 읽기 어려울 수 있습니다.

regex validation phone-number

regex validation phone number

무력화 없이 ASP.NET에서 'A potentially dangerous Request.Form value was detected from the client' 오류 해결: 3가지 실용적인 방법

"A potentially dangerous Request. Form value was detected from the client" 오류는 ASP. NET, 특히 ASP. NET MVC에서 사용자 입력 값을 처리할 때 발생하는 일반적인 오류입니다