TIL #77 : [Django] Email Validation

셀레스틴 허·2021년 2월 21일
0
post-thumbnail

정규표현식이 아닌, Django 내 validators 쓰기

승현님께 리뷰 받고 정규표현식이 아닌, Django에서 제공하는 validators를 쓰기로 했다!

기존 코드


import re

email_regex = re.compile(r'^[a-zA-Z0-9+-_.]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$')

if not email_regex.search(email):
                return JsonResponse({"message" : "INVALID_EMAIL"}, status=400)

re를 import해 사용자가 입력하는 이메일 값에 @,.이 포함되었는지 확인하는 로직이다.

고친 코드


from django.core.validators  import validate_email
from django.core.exceptions  import ValidationError

try:
  validate_email(email)
                
except ValidationError:
            return JsonResponse({"message" : "VALIDATION_ERROR"}, status=400)

HTTP REQUEST 보내기

http -v POST 127.0.0.1:8000/user/signup email="mjeuefu.com" name="ng" password="1234@kkkk" username="nteboook" phone="010-2939-0000"

요청 내용을 보면 @를 빼고 email 값을 넣었다. 로직대로라면..! "VALIDATION_ERROR"가 떠야한다.

RESULT

HTTP/1.1 400 Bad Request
Content-Length: 31
Content-Type: application/json
Date: Sun, 21 Feb 2021 03:14:43 GMT
Referrer-Policy: same-origin
Server: WSGIServer/0.2 CPython/3.9.1
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: DENY

{
    "message": "VALIDATION_ERROR"
}

🍒 성공 🐹

Reference:
https://stackoverflow.com/questions/13996622/django-how-to-check-if-something-is-an-email-without-a-form

profile
Software Developer / 고통은 필연, 괴로움은 선택

0개의 댓글