Integrations
Validate phone numbers and emails in Django
Add Django form validators that check emails and phone numbers through the API with requests. Show field errors, store E.164 and fail open on API errors.
Updated 2026-11-23
This recipe validates an email and a phone number inside a Django form, with errors shown next to the field. The same function works in Django REST Framework serializers.
What you need
- Django 4.2 or later, Python 3.9 or later and
pip install requests. - A Qelka API key in the
API_KEYenvironment variable. Ask_test_key returns simulated results and never spends credits: see Test mode. - Server-side code only: see Authentication.
Steps
1. Settings
In settings.py:
import os
API_KEY = os.environ["API_KEY"]
API_BASE_URL = "https://api.qelka.com/v1"
2. A client module
Save as yourapp/validation.py:
import logging
import random
import time
import requests
from django.conf import settings
logger = logging.getLogger(__name__)
RETRYABLE = {429, 500, 502, 503}
def call_api(path, body, max_attempts=3, timeout=10):
headers = {"Authorization": f"Bearer {settings.API_KEY}"}
for attempt in range(1, max_attempts + 1):
try:
response = requests.post(f"{settings.API_BASE_URL}{path}", headers=headers, json=body, timeout=timeout)
except requests.RequestException as error:
logger.warning("validation skipped: %s", error.__class__.__name__)
return None
if response.ok:
return response.json()
if response.status_code in RETRYABLE and attempt < max_attempts:
retry_after = response.headers.get("Retry-After", "")
time.sleep(int(retry_after) if retry_after.isdigit() else 2 ** (attempt - 1) + random.random() / 4)
continue
error = response.json().get("error", {})
logger.warning(
"validation skipped: %s status=%s request_id=%s",
error.get("type"),
response.status_code,
response.headers.get("X-Request-Id"),
)
return None
call_api returns None whenever the check could not complete, so every caller fails open. A 429 waits for Retry-After, and 500, 502 and 503 back off. The log line carries the documented error type and the request id, which support asks for. See Errors.
3. Validators
from django.core.exceptions import ValidationError
from .validation import call_api
def deliverable_email(value):
result = call_api("/email", {"email": value})
if result and result["status"] == "undeliverable":
suggestion = result["did_you_mean"]
raise ValidationError(f"Did you mean {suggestion}?" if suggestion else "This email address cannot receive mail.")
def valid_phone(value, country=None):
body = {"phone": value}
if country:
body["country"] = country
result = call_api("/phone", body)
if result and result["status"] == "invalid":
raise ValidationError("This phone number is not valid.")
return result["e164"] if result and result["status"] == "valid" else value
4. A form that uses them
from django import forms
from .validators import deliverable_email, valid_phone
class SignupForm(forms.Form):
email = forms.EmailField(validators=[deliverable_email])
phone = forms.CharField(max_length=64)
country = forms.CharField(min_length=2, max_length=2)
def clean(self):
cleaned = super().clean()
if cleaned.get("phone"):
try:
cleaned["phone"] = valid_phone(cleaned["phone"], cleaned.get("country"))
except forms.ValidationError as error:
self.add_error("phone", error)
return cleaned
EmailField runs Django's own syntax check before the validator, so malformed input never costs a call. After clean, cleaned_data["phone"] holds the E.164 number when the API confirmed it. Store that, not what was typed.
5. Flag risky IPs in the view
from .validation import call_api
def signup(request):
form = SignupForm(request.POST or None)
if request.method == "POST" and form.is_valid():
ip = request.META.get("REMOTE_ADDR")
lookup = call_api("/ip", {"ip": ip}) if ip else None
needs_review = bool(lookup and (lookup["risk"]["level"] == "high" or lookup["flags"]["tor"]))
create_account(form.cleaned_data, needs_review=needs_review)
create_account is your own function. A high risk level means ask for extra verification, not refuse: VPNs and corporate networks are everyday tools. On 127.0.0.1 the API answers 422, which call_api logs and turns into None.
6. Read the result
| Result | Action |
|---|---|
Email undeliverable |
Field error with did_you_mean |
Email risky or unknown |
Accept, confirm by email |
Phone invalid |
Field error |
Phone unknown |
Send the country field |
Phone valid |
Store e164 |
The request flow is the same for every form: Django's own field checks run first, then the API check, then your save logic. Because call_api never raises, a slow or failed check cannot break the page, and the person is never asked to retry because of our side.
Rate limits are 200 requests per 10 seconds per key: see Rate limits. Throttle your signup view, for example with a cache-based counter per IP, so bots cannot spend your credits through your form. Store each result next to the record when you can, so a repeated value is never checked twice.
Related
Frequently asked questions
Validator, form clean method or signal?
How do I read the client IP in Django?
Where should the API key be stored?
Put this check in your product
Get an API key in under a minute. 100 free credits every month, no card required.
- 100 free credits a month
- No card
- Test keys spend nothing
- Cancel any time