Category: Python

  • Validate Ecuador’s Cédula and RUC in Python and JavaScript

    If your app has users or customers in Ecuador, sooner or later a form will ask for a cédula (the national ID number) or a RUC (the taxpayer number every business and freelancer needs to issue an invoice). Both carry a check digit, so you can reject typos before they reach your database, or a tax authority that will reject the invoice for you.

    Most snippets you’ll find online only cover half of it. They validate the cédula and assume every RUC works the same way, or they skip the province check and happily accept 0000000000. I shipped exactly that bug in a loan management system, and later had to handle all three RUC types in an e-invoicing app. The code below is a clean rewrite of what I ended up with.

    This post gives you a complete validator in Python and JavaScript, the tests to prove it, and the mistakes worth avoiding.

    What you can (and can’t) check

    A check digit tells you a number is well-formed. It doesn’t tell you it exists: anyone can generate a number that passes. If you need to know that a RUC is actually registered, you have to query Ecuador’s tax authority (SRI). Validation is the cheap first filter.

    A cédula has 10 digits:

    PositionMeaning
    1–2Province code: 01 to 24, or 30 for Ecuadorians abroad
    3Below 6 for a natural person
    4–9Sequence number
    10Check digit (mod 10)

    Don’t forget 30: real cédulas start with it, and a validator that only accepts 01 to 24 rejects them.

    A RUC has 13 digits, and its third digit tells you which algorithm applies:

    Type3rd digitAlgorithmCheck digit atSuffix
    Natural person0–5Mod 10 (it’s the cédula)Position 10Last 3, not 000
    Public entity6Mod 11, weights 3 2 7 6 5 4 3 2Position 9Last 4, not 0000
    Private company9Mod 11, weights 4 3 2 7 6 5 4 3 2Position 10Last 3, not 000

    A natural person’s RUC is just their cédula plus an establishment number, and 001 is the main one. So 1712345675 (a made-up cédula) becomes the RUC 1712345675001.

    Step 1: normalize, then check the shape

    Users type dashes and trailing spaces. Strip those and nothing else; anything that still isn’t 10 or 13 ASCII digits is invalid.

    def normalize(value):
        """'171234567-5 ' -> '1712345675'."""
        return (value or "").replace(" ", "").replace("-", "")
    
    
    def _is_digits(value, length):
        # isascii() keeps '²' and other Unicode digits out.
        return len(value) == length and value.isascii() and value.isdigit()
    
    
    def _valid_province(value):
        province = int(value[:2])
        return 1 <= province <= 24 or province == 30

    Why isascii()? Because "²".isdigit() is True in Python, and int("²") raises ValueError. One odd character pasted from a PDF and your endpoint returns a 500.

    Step 2: the cédula (mod 10)

    Multiply the first nine digits by 2 1 2 1 2 1 2 1 2, subtract 9 from any product above 9, and add everything up. The check digit is (10 - total % 10) % 10.

    For 1712345675 the products are 2 7 2 2 6 4 1 6 5 (the 10 and the 14 become 1 and 5), the total is 35, and 10 - 5 = 5 matches the last digit.

    CEDULA_WEIGHTS = (2, 1, 2, 1, 2, 1, 2, 1, 2)
    
    
    def is_valid_cedula(cedula):
        if not _is_digits(cedula, 10) or not _valid_province(cedula):
            return False
        if int(cedula[2]) >= 6:
            return False
        total = 0
        for digit, weight in zip(cedula[:9], CEDULA_WEIGHTS):
            product = int(digit) * weight
            total += product - 9 if product > 9 else product
        return (10 - total % 10) % 10 == int(cedula[9])

    If you’ve implemented Luhn before, this will look familiar: subtracting 9 is the same as adding the two digits of the product.

    Step 3: the RUC, by type

    Mod 11 uses different weights and no “subtract 9” step. Take the weighted sum, compute remainder = total % 11; the check digit is 0 when the remainder is 0, and 11 - remainder otherwise.

    A remainder of 1 gives 10, which can’t be a single digit, so that number simply can’t be a valid RUC. The function below handles it for free, since 10 never equals a digit.

    PRIVATE_WEIGHTS = (4, 3, 2, 7, 6, 5, 4, 3, 2)
    PUBLIC_WEIGHTS = (3, 2, 7, 6, 5, 4, 3, 2)
    
    
    def _mod11(digits, weights):
        remainder = sum(int(d) * w for d, w in zip(digits, weights)) % 11
        return 0 if remainder == 0 else 11 - remainder  # 10 never matches: invalid
    
    
    def ruc_type(ruc):
        """'natural', 'public', 'private', or None if the RUC is malformed."""
        if not _is_digits(ruc, 13) or not _valid_province(ruc):
            return None
        third = int(ruc[2])
        if third < 6:
            ok = is_valid_cedula(ruc[:10]) and ruc[10:] != "000"
            return "natural" if ok else None
        if third == 6:
            ok = _mod11(ruc[:8], PUBLIC_WEIGHTS) == int(ruc[8]) and ruc[9:] != "0000"
            return "public" if ok else None
        if third == 9:
            ok = _mod11(ruc[:9], PRIVATE_WEIGHTS) == int(ruc[9]) and ruc[10:] != "000"
            return "private" if ok else None
        return None
    
    
    def is_valid_ruc(ruc):
        return ruc_type(ruc) is not None

    Returning the type instead of a bare boolean pays off later: invoicing code usually needs to know whether the buyer is a person or a company.

    Step 4: test it

    All numbers here are made up. They satisfy the algorithm; they were not looked up anywhere.

    assert is_valid_cedula("1712345675")
    assert is_valid_cedula("0923456784")             # leading zero: keep it a string
    assert not is_valid_cedula("1712345674")         # wrong check digit
    assert not is_valid_cedula("0000000000")         # province 00
    assert not is_valid_cedula("2512345678")         # province 25 doesn't exist
    assert not is_valid_cedula("1772345678")         # third digit 7
    assert not is_valid_cedula("17123456²5")         # Unicode digit
    assert is_valid_cedula(normalize(" 171234567-5 "))
    
    assert ruc_type("1712345675001") == "natural"
    assert ruc_type("1712345675000") is None         # suffix 000
    assert ruc_type("1791234561001") == "private"
    assert ruc_type("1765432130001") == "public"
    assert ruc_type("1760123400001") is None         # remainder 1: no possible digit
    assert not is_valid_ruc("1712345675")            # a cédula is not a RUC
    print("ok")

    Step 5: the same thing in JavaScript

    Use it in the browser for instant feedback, never as the only check. The server has the final word.

    const CEDULA_WEIGHTS = [2, 1, 2, 1, 2, 1, 2, 1, 2];
    const PRIVATE_WEIGHTS = [4, 3, 2, 7, 6, 5, 4, 3, 2];
    const PUBLIC_WEIGHTS = [3, 2, 7, 6, 5, 4, 3, 2];
    
    export const normalize = (value) => String(value ?? '').replace(/[\s-]/g, '');
    
    // typeof: a number would drop the leading zero. In JavaScript, \d only matches 0-9.
    const isDigits = (value, length) =>
      typeof value === 'string' && new RegExp(`^\\d{${length}}$`).test(value);
    
    function validProvince(value) {
      const province = Number(value.slice(0, 2));
      return (province >= 1 && province <= 24) || province === 30;
    }
    
    function mod11(value, weights) {
      const total = weights.reduce((acc, w, i) => acc + Number(value[i]) * w, 0);
      const remainder = total % 11;
      return remainder === 0 ? 0 : 11 - remainder;
    }
    
    export function isValidCedula(cedula) {
      if (!isDigits(cedula, 10) || !validProvince(cedula)) return false;
      if (Number(cedula[2]) >= 6) return false;
      let total = 0;
      CEDULA_WEIGHTS.forEach((w, i) => {
        const product = Number(cedula[i]) * w;
        total += product > 9 ? product - 9 : product;
      });
      return (10 - (total % 10)) % 10 === Number(cedula[9]);
    }
    
    export function rucType(ruc) {
      if (!isDigits(ruc, 13) || !validProvince(ruc)) return null;
      const third = Number(ruc[2]);
      if (third < 6) {
        return isValidCedula(ruc.slice(0, 10)) && ruc.slice(10) !== '000' ? 'natural' : null;
      }
      if (third === 6) {
        return mod11(ruc, PUBLIC_WEIGHTS) === Number(ruc[8]) && ruc.slice(9) !== '0000' ? 'public' : null;
      }
      if (third === 9) {
        return mod11(ruc, PRIVATE_WEIGHTS) === Number(ruc[9]) && ruc.slice(10) !== '000' ? 'private' : null;
      }
      return null;
    }
    
    export const isValidRuc = (ruc) => rucType(ruc) !== null;

    The typeof check is there on purpose: /^\d{10}$/.test(923456784) would coerce the number to a string, and a cédula from province 09 would already have lost its leading zero.

    Step 6: wire it into Django

    A model-level validator covers ModelForms, the admin and full_clean() in one place:

    from django.core.exceptions import ValidationError
    from django.db import models
    
    from .ecuador_ids import is_valid_cedula
    
    
    def validate_cedula(value):
        if not is_valid_cedula(value):
            raise ValidationError("Enter a valid Ecuadorian cédula.", code="invalid_cedula")
    
    
    class Customer(models.Model):
        cedula = models.CharField(max_length=10, unique=True, validators=[validate_cedula])

    If one field accepts either ID (a buyer on an invoice, for example), branch on length: 10 digits is a cédula, 13 is a RUC, and anything else, like a passport number, gets its own rules.

    Common pitfalls

    Only checking the check digit. 0000000000 sums to 0, the expected digit is 0, and it passes. That’s the bug I shipped. The province and third-digit rules catch it.

    Storing IDs as integers. Anyone from provinces 01–09 has a cédula starting with zero. An IntegerField or a JavaScript Number silently drops it. IDs are strings.

    Using isdigit() alone. It accepts Unicode digits that int() can’t parse. Pair it with isascii() or use a regex.

    Running mod 10 on every RUC. Only natural-person RUCs embed a cédula. Companies and public entities use mod 11, with different weights and the check digit in a different position.

    Treating “valid” as “registered”. A check digit can’t tell you a business exists. If you’re issuing invoices, confirm against the SRI’s taxpayer registry. Note that it indexes RUCs, not cédulas: to look up a person, query their cédula followed by 001.

    Hard-rejecting company RUCs on the check digit. The SRI doesn’t publish the check-digit algorithm for company RUCs, and an unofficial guide (in Spanish) says some recent ones don’t pass mod 11. I couldn’t confirm that with an official source, but getting it wrong means turning away a real customer. If you can query the registry, when ruc_type returns None for a RUC whose third digit is 9, show a warning and let the registry decide.

    Assuming Django validators run on save(). They don’t. They run in forms, the admin and full_clean(). If you create records from a script or an API view, call full_clean() yourself.

    Wrapping up

    Validating Ecuadorian IDs takes about 50 lines, not counting the tests: normalize, check length, province and third digit, then apply mod 10 or mod 11 depending on the type. The parts that bite are the edges: leading zeros, Unicode digits, and the gap between a well-formed number and a registered one.

    Copy the Python or JavaScript version above, keep the tests next to it, and you have one less source of rejected invoices.