# Validate signup forms

A signup form is the cheapest place to catch bad data: the person is still there to fix a typo. This guide builds a server-side check that runs when the form is submitted, in one API call, and turns the results into three outcomes: accept, ask for a correction, or accept and flag for review.

## What to check

| Field | What the check catches | Endpoint | Credits |
|---|---|---|---|
| Email | Typos in the domain, domains that cannot receive mail, mailboxes that do not exist, disposable inboxes | [/email](/docs/api-reference/email) | 1 |
| Phone, if you ask for one | Impossible numbers, missing country codes; gives you the E.164 form to store | [/phone](/docs/api-reference/phone) | 1 at the basic level |
| IP address | Signups from Tor, known VPNs and data centers, as a signal for review | [/ip](/docs/api-reference/ip) | 1 |

A [batch](/docs/api-reference/batch) runs the three checks in one request, so a signup with all three costs 1 + 1 + 1 credits and one round trip.

## Ground rules

- **Check on submit, on your server.** Not on every keystroke: each call costs credits, cached or not. And not from the browser: your API key must stay secret.
- **Fail open.** If the API is slow or unreachable, let the signup through and check later. A validation service should never be the reason nobody can sign up. Give the call a timeout.
- **Never block on `unknown`.** It means the check could not reach a conclusion, not that the address is bad. Large providers often do not reveal whether a mailbox exists.
- **Keep the confirmation email.** The API catches many bad addresses before you send it. The confirmation email remains the proof that the person controls the inbox.

## Decide what to do with each email status

| `status` | `reason` | At signup |
|---|---|---|
| `deliverable` | `accepted_email` | Accept. |
| `undeliverable` | `invalid_syntax`, `domain_not_found`, `domain_no_mx`, `domain_null_mx` | Ask for a correction. Show `did_you_mean` when there is one. |
| `undeliverable` | `mailbox_not_found`, `mailbox_disabled` | Ask the person to check the address or use another one. |
| `risky` | `disposable` | Your call: reject with a clear message, or accept and flag. See [Block disposable email signups](/docs/guides/block-disposable-signups). |
| `risky` | `catch_all` | Accept. The domain accepts every address, so the mailbox cannot be confirmed; the confirmation email settles it. |
| `risky` | `mailbox_full` | Accept. The mailbox exists but is full, so your confirmation email may bounce until its owner makes room. |
| `unknown` | any | Accept. Optionally check again later with `"fresh": true`. |

Role addresses such as `info@` or `sales@` keep their status. Whether to accept them is a product decision: fine for a newsletter, perhaps not for a personal account. They come with `checks.role: true`.

## Decide what to do with the phone number

| Result | At signup |
|---|---|
| `status: "valid"` | Accept and store `e164`, not what was typed. |
| `status: "invalid"` | Ask for a correction. |
| `status: "unknown"` | The number was typed without a `+` country code and you did not send `country`. Send the country the person picked in the form, or ask for the international format. |

The basic level is enough at signup. The live level, at 3 credits, adds the current carrier and porting status, which a signup rarely needs.

## Decide what to do with the IP address

Use the IP result to decide how much friction to add, not whether a person may sign up: VPNs and corporate networks are everyday tools. A high `risk.level` or a Tor exit node is a reason to flag the account for review or to ask for an extra verification step. [Flag VPN and data center traffic](/docs/guides/flag-vpn-and-datacenter-traffic) covers the details, including how to read the right client address behind a proxy.

## The code

A function that takes the form fields and the client IP address, and returns a verdict:

```javascript
const API = 'https://api.qelka.com/v1'

export async function checkSignup({ email, phone, country, ip }) {
  if (!email || email.length > 320) {
    return { ok: false, checked: false, errors: [{ field: 'email', message: 'Enter a valid email address.' }], e164: null, review: false }
  }

  const items = [{ type: 'email', email }]
  if (phone && phone.length <= 64) {
    items.push(/^[A-Za-z]{2}$/.test(country ?? '') ? { type: 'phone', phone, country } : { type: 'phone', phone })
  }
  if (ip) items.push({ type: 'ip', ip })

  let data
  try {
    const response = await fetch(`${API}/batch`, {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${process.env.API_KEY}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ items }),
      signal: AbortSignal.timeout(10000),
    })
    if (!response.ok) return { ok: true, checked: false, errors: [], e164: null, review: false }
    data = (await response.json()).data
  } catch {
    return { ok: true, checked: false, errors: [], e164: null, review: false }
  }

  const results = Object.fromEntries(items.map((item, index) => [item.type, data[index]]))
  const errors = []
  let e164 = null
  let review = false

  const emailResult = results.email
  if (emailResult.object === 'email') {
    if (emailResult.status === 'undeliverable') {
      errors.push({
        field: 'email',
        message: emailResult.did_you_mean
          ? `Did you mean ${emailResult.did_you_mean}?`
          : 'This address cannot receive email. Please check it.',
      })
    } else if (emailResult.checks.disposable) {
      errors.push({ field: 'email', message: 'Please use a permanent email address.' })
    }
  }

  const phoneResult = results.phone
  if (phoneResult?.object === 'phone') {
    if (phoneResult.status === 'unknown') {
      errors.push({ field: 'phone', message: 'Add your country code, or pick your country.' })
    } else if (!phoneResult.valid) {
      errors.push({ field: 'phone', message: 'This phone number is not valid. Please check it.' })
    } else {
      e164 = phoneResult.e164
    }
  }

  const ipResult = results.ip
  if (ipResult?.object === 'ip') {
    review = ipResult.risk.level === 'high' || ipResult.flags.tor
  }

  return { ok: errors.length === 0, checked: true, errors, e164, review }
}
```

What it does:

- One batch call, with a 10-second timeout. Email items run in `full` mode by default, which waits for the mail server; the timeout keeps a slow server from holding the form.
- Every failure path returns `ok: true` with `checked: false`: the signup goes through, and you can check it again later.
- Items that fail inside the batch, such as a private IP address during local development, come back as error objects. The code reads the `object` field and ignores them.
- Each result is matched to its item by position: `data[i]` always answers `items[i]`.

Wired into an Express route:

```javascript
import express from 'express'
import { checkSignup } from './check-signup.js'

const app = express()
app.set('trust proxy', 1)

app.post('/signup', express.json(), async (req, res) => {
  const verdict = await checkSignup({
    email: req.body.email,
    phone: req.body.phone,
    country: req.body.country,
    ip: req.ip,
  })
  if (!verdict.ok) return res.status(422).json({ errors: verdict.errors })
  const user = await createUser({
    email: req.body.email,
    phone: verdict.e164 ?? req.body.phone,
    needsReview: verdict.review,
    needsRecheck: !verdict.checked,
  })
  res.status(201).json({ id: user.id })
})
```

`createUser` stands for your own account creation code. `trust proxy` tells Express to read the client address from the `X-Forwarded-For` header set by one proxy in front of it; set it to match your setup, or `req.ip` will be the proxy's address.

## The same check in Python

```python
import os

import requests

API = "https://api.qelka.com/v1"


def check_signup(email, phone=None, country=None, ip=None):
    items = [{"type": "email", "email": email}]
    if phone:
        items.append({"type": "phone", "phone": phone, **({"country": country} if country else {})})
    if ip:
        items.append({"type": "ip", "ip": ip})
    try:
        response = requests.post(
            f"{API}/batch",
            headers={"Authorization": f"Bearer {os.environ['API_KEY']}"},
            json={"items": items},
            timeout=10,
        )
    except requests.RequestException:
        return {"ok": True, "checked": False, "errors": []}
    if not response.ok:
        return {"ok": True, "checked": False, "errors": []}
    results = {item["type"]: entry for item, entry in zip(items, response.json()["data"])}
    errors = []
    email_result = results["email"]
    if email_result["object"] == "email":
        if email_result["status"] == "undeliverable":
            suggestion = email_result["did_you_mean"]
            errors.append({"field": "email", "message": f"Did you mean {suggestion}?" if suggestion else "This address cannot receive email."})
        elif email_result["checks"]["disposable"]:
            errors.append({"field": "email", "message": "Please use a permanent email address."})
    phone_result = results.get("phone")
    if phone_result and phone_result["object"] == "phone" and not phone_result["valid"]:
        errors.append({"field": "phone", "message": "This phone number is not valid."})
    return {"ok": not errors, "checked": True, "errors": errors}
```

## Show the suggestion well

When `did_you_mean` is set, show it as a question with a one-click fix: "Did you mean jane@gmail.com?" Let the person accept it; do not replace the address silently. Some people really do have unusual domains.

## If a few seconds matter

A full-mode email check waits for the recipient's mail server, which can take a few seconds. If that is too long for your form:

1. Send the email item with `"mode": "fast"` at submit. It catches typos, dead domains and disposable inboxes without waiting for a mail server.
2. Create the account, then run a `full` check in the background and act on the result, for example before sending anything other than the confirmation email.

The two calls cost 1 credit each.

## Test it

With a test key, the part of an email address before the `@` picks the outcome: `undeliverable@example.com` comes back `undeliverable`, `disposable@example.com` is flagged as disposable, `unknown@example.com` comes back `unknown`, and any other well-formed address `deliverable`. Phone numbers are parsed for real, and the IP address `198.51.100.200` returns a Tor exit node with a `high` risk level. That exercises every branch of the code without spending credits. See [Test mode](/docs/test-mode).
