PDF VectorPDF Vector
Back to all articles

How to Validate Extracted Invoice Data

Validate extracted invoice data in three layers: field checks, invoice arithmetic and cross-system checks, with Python code and a retry-then-review policy.

How to Validate Extracted Invoice Data

Extracted invoice data should never go straight from an OCR or AI step into your books. Validate it in three layers: field checks (is each value present and well formed), document checks (does the invoice's own arithmetic hold), and cross-system checks (does it match your vendor master, your purchase orders and what you have already paid). Anything that fails is retried once with a stronger extraction model and then sent to a person with a specific reason. This guide gives the rules for each layer, working Python code, and a routing policy you can run on every invoice.

Why extracted invoice data needs its own checks

Whatever does the reading (template OCR, an AI extraction API or a person) makes predictable mistakes:

  • Digit errors. A scan turns 8 into 3, or 1,250.00 into 125.00. The value looks plausible and passes a type check.
  • Wrong total. On a multi-page invoice, a page subtotal or the amount before tax is taken as the total.
  • Missed or extra lines. A line item that continues onto the next page is dropped, a "continued" row or a section subtotal is counted as a line, or a line appears twice.
  • Sign and format errors. Credit notes lose their minus sign; 1.234,56 becomes 1.23456; 03/04 is read as March 4 when the vendor meant April 3.
  • Right value, wrong field. The PO number lands in the invoice number field, or the customer's address is taken as the vendor's.

None of these is visible without checking, and each one costs time downstream: wrong payments, supplier disputes, failed reconciliations and audit questions. AI extraction APIs, including PDF Vector, return the data without a per-field confidence score, so the checks are what tells you whether to trust a result.

Start with a schema that makes validation possible

You can only check what you extract. Ask for the fields that let the invoice prove itself, not only the ones your ERP needs:

  • subtotal, discount, tax and total as separate numbers, so the totals equation can be checked.
  • quantity, unitPrice and amount per line, so each line can be checked.
  • currency as an ISO 4217 code and dates as YYYY-MM-DD, so formats can be checked strictly.
  • vendorTaxId and payment details (IBAN or account number) when your invoices carry them, so the vendor can be matched against your master data.
  • poNumber when you use purchase orders.

Mark the fields you cannot post without as required in the JSON Schema. A good extraction prompt also states conventions, for example "amounts as plain numbers, negative for credit notes; use 0 when there is no tax line". The invoice-to-JSON guide walks through building the schema and the request with Invoice Extract; the JSON Schema Editor helps if you prefer not to write JSON Schema by hand.

Layer 1: field-level checks

These are cheap and catch the obvious problems:

FieldCheckTypical failure it catches
Invoice numberPresent, non-empty, no spaces onlyMissed header field
Vendor name / tax IDPresent; tax ID matches the country's formatCustomer details taken as vendor
Invoice dateValid YYYY-MM-DD, not in the future, not older than your cutoff (for example 18 months)Day/month swap, wrong year
Due dateOn or after the invoice dateDay/month swap
CurrencyIn the list of currencies you pay inSymbol misread, wrong default
AmountsNumbers, at most 2 decimals (or your currency's minor units), total not zeroFormat errors such as 1.23456
Line itemsAt least one, each with a description and an amountTable not read at all

Tax ID formats are country specific. An EU VAT number starts with a two-letter country code and can be checked against the EU's VIES service; for others, a regular expression per country is usually enough at this stage.

Layer 2: document-level arithmetic

Invoices carry their own checksum. Use all of it:

  1. Line arithmetic: quantity × unitPrice = amount for each line (allow rounding of one minor unit).
  2. Line sum: the line amounts add up to the subtotal.
  3. Totals equation: subtotal − discount + tax = total.
  4. Tax rate plausibility: tax / (subtotal − discount) is one of the rates you expect for that vendor or country (for example 0%, 5%, 10%, 20%), within a small tolerance.
  5. Sign consistency: on a credit note, all of subtotal, tax and total are negative; on an invoice, all positive.

Check 2 is the one that catches dropped and duplicated lines on multi-page invoices. Check 3 catches a subtotal taken as the total. Check 4 catches a tax figure that balances the equation but makes no sense, for example a shipping or service charge read as tax, with the subtotal shifted to compensate.

Some layouts need adjusted formulas: tax-inclusive line prices (common on receipts), per-line discounts, shipping or fee lines outside the line table, and withholding taxes deducted from the total. Handle them with per-vendor settings rather than switching the checks off.

Layer 3: cross-document and cross-system checks

An invoice can be internally consistent and still wrong for your business. These checks compare it with what you already know:

  • Duplicate detection. Normalize the invoice number (uppercase, strip spaces, dashes and leading zeros) and look up vendor + normalized number in your AP system. Also flag near-duplicates: same vendor, same total, invoice dates within a few days. Suppliers resend invoices and mail rules fire twice.
  • Vendor master match. The vendor's tax ID or name must match an approved vendor. A new vendor needs a person, both for data quality and for fraud control.
  • Bank detail changes. If the extracted IBAN or account number differs from the one on file for that vendor, hold the invoice. Changed payment details on an otherwise normal invoice are a classic fraud pattern, and extraction makes it easy to check every time.
  • PO and receipt matching. With purchase orders, compare the invoice to the PO (two-way match) or to the PO and goods receipt (three-way match): same vendor, quantities not above what was received, unit prices within tolerance of the PO price.
  • Expected ranges. Compare the total with that vendor's history. A utility bill ten times the usual amount may be correct, but a person should see it.
  • Approval thresholds. Above an amount you set, route to approval even when every check passes.

Python: a validator you can run on every invoice

The code below implements layers 1 and 2 and the duplicate check from layer 3. It uses Decimal, because floats produce false alarms on money (0.1 + 0.2 is not 0.3 in binary floating point).

from datetime import date, timedelta
from decimal import Decimal, ROUND_HALF_UP
import re

CENT = Decimal("0.01")
ALLOWED_CURRENCIES = {"USD", "EUR", "GBP"}
EXPECTED_TAX_RATES = [Decimal(r) for r in ("0", "0.05", "0.10", "0.20")]


def money(value):
    return Decimal(str(value)).quantize(CENT, rounding=ROUND_HALF_UP)


def parse_date(value):
    if not isinstance(value, str) or not re.fullmatch(r"\d{4}-\d{2}-\d{2}", value):
        return None
    try:
        return date.fromisoformat(value)
    except ValueError:
        return None


def normalize_number(value):
    return re.sub(r"[\s\-_/]", "", str(value or "")).upper().lstrip("0")


def validate_invoice(inv, seen_keys=frozenset()):
    """Return a list of problems; an empty list means the invoice passed."""
    problems = []

    # Layer 1: fields
    for field in ("vendorName", "invoiceNumber", "invoiceDate", "total"):
        if inv.get(field) in (None, ""):
            problems.append(f"missing {field}")
    if problems:
        return problems

    inv_date = parse_date(inv["invoiceDate"])
    if inv_date is None:
        problems.append(f"bad invoice date: {inv['invoiceDate']}")
    elif inv_date > date.today() or inv_date < date.today() - timedelta(days=550):
        problems.append(f"invoice date out of range: {inv_date}")

    due = parse_date(inv.get("dueDate")) if inv.get("dueDate") else None
    if inv_date and due and due < inv_date:
        problems.append(f"due date {due} before invoice date {inv_date}")

    if inv.get("currency") not in ALLOWED_CURRENCIES:
        problems.append(f"unexpected currency: {inv.get('currency')}")

    # Layer 2: arithmetic
    total = money(inv["total"])
    tax = money(inv.get("tax") or 0)
    discount = money(inv.get("discount") or 0)
    lines = inv.get("lineItems") or []
    if not lines:
        problems.append("no line items")

    incomplete = [i for i, li in enumerate(lines, start=1)
                  if not li.get("description") or li.get("amount") is None]
    if incomplete:
        problems.append(f"lines missing description or amount: {incomplete}")
        return problems

    for i, li in enumerate(lines, start=1):
        if li.get("quantity") is not None and li.get("unitPrice") is not None:
            expected = money(Decimal(str(li["quantity"])) * Decimal(str(li["unitPrice"])))
            if abs(expected - money(li["amount"])) > CENT:
                problems.append(f"line {i}: {li['quantity']} x {li['unitPrice']} = {expected}, got {li['amount']}")

    line_sum = sum((money(li["amount"]) for li in lines), Decimal("0"))
    if inv.get("subtotal") is not None:
        subtotal = money(inv["subtotal"])
        if lines and abs(line_sum - subtotal) > CENT:
            problems.append(f"lines sum to {line_sum}, subtotal is {subtotal}")
        if abs(subtotal - discount + tax - total) > CENT:
            problems.append(f"{subtotal} - {discount} + {tax} = {subtotal - discount + tax}, total is {total}")
        base = subtotal - discount
        if base != 0 and tax != 0:
            rate = tax / base
            if not any(abs(rate - r) <= Decimal("0.005") for r in EXPECTED_TAX_RATES):
                problems.append(f"unusual tax rate {rate:.4f}")

    sign_values = [total, tax]
    if inv.get("subtotal") is not None:
        sign_values.append(money(inv["subtotal"]))
    signs = {v > 0 for v in sign_values if v != 0}
    if len(signs) > 1:
        problems.append("mixed signs between subtotal, tax and total")

    # Layer 3: duplicates
    key = (inv["vendorName"].strip().lower(), normalize_number(inv["invoiceNumber"]))
    if key in seen_keys:
        problems.append(f"duplicate of an invoice already processed: {key}")

    return problems

Feed it the data object returned by an extraction call. seen_keys would come from your AP system or a table of processed invoices; in production, run the vendor-master, bank-detail and PO checks against your own databases at the same point.

What to do when a check fails

Not every failure needs a person. A policy that works well:

  1. Missing or malformed fields, or failed arithmetic: retry the extraction once on a higher tier. With PDF Vector that means resending the same file with model: "pro" or "max". Poor scans and dense multi-page tables are where higher tiers help most.
  2. Still failing after the retry: send to review with the list of problems. "Lines sum to 4,180.00, subtotal is 4,380.00" tells the reviewer to look for a missing 200.00 line, which is much faster than re-keying the invoice.
  3. Cross-system failures (duplicate, unknown vendor, changed bank details, PO mismatch): do not retry. The extraction is probably right and the business question needs a person.
  4. Passed everything but above the approval threshold: route to approval, not to review.

The retry costs credits, so it is worth knowing the numbers. Invoice Extract costs 6, 10, 14 or 18 credits per page on nano, mini, pro and max. A three-page invoice extracted on mini and retried on max costs 3 × 10 + 3 × 18 = 84 credits; without the retry, 30. Requests that end in an error are not charged.

A second opinion as a confidence signal

Since there is no confidence score, some teams extract high-value invoices twice, for example on mini and max, and compare the fields. If both runs agree on vendor, number, date and total, confidence is high; if they disagree, a person decides. It nearly triples the cost of those invoices (28 instead of 10 credits per page for mini + max), so reserve it for amounts above a threshold.

Track validation results over time

Store every check result next to the invoice: the problems found, the model tier that ran, whether a retry happened and the final outcome (posted automatically, corrected in review, rejected). Then watch:

  • Pass rate per vendor. A vendor whose invoices fail often needs a prompt tweak (for example, explaining their discount layout) or a per-vendor rule.
  • Which check fails most. Many line-sum failures point to multi-page tables; many date failures point to day/month ambiguity that the prompt should resolve ("dates on these invoices are DD/MM/YYYY").
  • Corrections in review. Fields that reviewers change most often are where to focus.

This turns validation from a gate into a feedback loop, and gives auditors a record of what was checked and why each invoice was accepted.

Applying the checks in no-code tools

The same rules work in Zapier, Make and n8n: a Code step after the extraction action calculates the checks and sets a valid flag, and a router or IF step sends failures to review. The Zapier, Make and n8n invoice guide has a Code step for each, and the n8n invoice workflow adds the retry on a higher model. For bank statements, the equivalent check is opening balance plus credits minus debits equals the closing balance; see the bank statement parsing guide. For the wider accounts payable process, see the accounts payable use case.

FAQ

How do I validate data extracted from invoices?

Check fields (present and well formed), the invoice's arithmetic (lines sum to subtotal; subtotal minus discount plus tax equals total), and your own records (duplicates, vendor master, POs). Retry failures once on a stronger model, then send them to review.

What is the most useful single check?

Line items summing to the subtotal, together with subtotal plus tax equalling the total. Together they catch missed lines, duplicated lines and a subtotal taken as the total.

Should I use floats for invoice amounts?

No. Use a decimal type (Python Decimal, or integer cents) so rounding does not produce false mismatches.

Do AI extraction APIs return confidence scores?

Some do; PDF Vector does not. Its output is the JSON you asked for, and the validation rules decide whether it posts automatically.

How do I catch duplicate invoices?

Normalize the invoice number (case, spaces, dashes, leading zeros) and look up vendor plus number before posting. Also flag same vendor, same total and close dates as possible duplicates.

What should happen to an invoice that fails validation?

Retry extraction on a higher tier if the failure is about missing fields or arithmetic. If it still fails, or the failure is about duplicates, vendors or POs, send it to a person with the specific problems listed.