Skip to content

One RUT rule for your API schema, your database and zod

`RUT_PATTERN` exports the exact RUT shapes rut.ts accepts as regex strings, so OpenAPI, JSON Schema, zod and a database CHECK all enforce the same rule as `validate()`.

Arrow Software Team
Arrow Software TeamNovember 6, 2026 · 7 min read
Server racks with orange and blue network cables behind mesh doors
The same rule has to hold in every system a RUT passes through. Source: Unsplash.

A RUT rule rarely lives in one place. The form validates it, the API contract describes it, the database stores it, and a reporting job in another language reads it back. validate() covers the first of those. The other three cannot run a TypeScript function, so the rule gets retyped there as a regular expression — and every retyped copy is a chance to get it slightly wrong. RUT_PATTERN, new in rut.ts 5.1.0, gives those places the exact shape rule the library enforces.

What is RUT_PATTERN?#

RUT_PATTERN is an object with four regular-expression strings: compact, hyphen, dotted and any. Each one matches exactly the RUT shape that validate() accepts, with the 7–8 digit body and the no-leading-zero rule built in. They are plain strings — anchored, flagless and backslash-free — so they paste into an OpenAPI spec, a zod schema or a SQL constraint without escaping. They check shape only: the verifier digit still needs validate().

TypeScript
import { RUT_PATTERN } from "rut.ts";
 
RUT_PATTERN.compact; // "^[1-9][0-9]{6,7}[0-9kK]$"                      123456785
RUT_PATTERN.hyphen;  // "^[1-9][0-9]{6,7}-[0-9kK]$"                     12345678-5
RUT_PATTERN.dotted;  // "^[1-9][0-9]?[.][0-9]{3}[.][0-9]{3}-[0-9kK]$"   12.345.678-5
RUT_PATTERN.any;     // any of the three

Why hand-written RUT regexes drift#

Writing ^\d{7,8}-[\dkK]$ takes ten seconds and looks right. It differs from the validator in three ways that only show up in production data.

It accepts leading zeros. 01234567-4 matches \d{7,8}, but validate('01234567-4') is false: a canonical RUT has no padding, and padding creates an unbounded family of strings for one identity. A column guarded by that regex will happily store two spellings of the same person.

The dotted version accepts 9-digit bodies. ^\d{1,3}\.\d{3}\.\d{3}-[\dkK]$ matches 123.456.789-5. No RUT has a nine-digit body, and validate() rejects it.

\d is not [0-9] everywhere. In Python's re and in Perl, \d also matches digits from other scripts, so 12345678-5 written in fullwidth digits passes the same pattern that JavaScript rejects. The moment the regex leaves the browser, its meaning changes.

None of these is exotic. They are the difference between "looks like a RUT" as a person reads it and the precise rule the validator applies. RUT_PATTERN closes that gap by construction: a test suite in the library checks that new RegExp(RUT_PATTERN.any).test(s.trim()) and isRutLike(s) agree, exhaustively over 2.4 million short strings and over thousands of mutated real RUTs. If either side changes alone, the build fails.

In an API contract#

An OpenAPI or JSON Schema pattern is the first thing an integrator reads, and code generators turn it into client-side checks for free. Build the component from the constant so it can never go stale:

TypeScript
import { RUT_PATTERN } from "rut.ts";
 
export const RutSchema = {
  type: "string",
  description: "Chilean RUT with hyphen, no dots",
  pattern: RUT_PATTERN.hyphen,
  maxLength: 10,
  example: "12345678-5",
} as const;

Which renders in the published spec as:

yaml
rut:
  type: string
  description: Chilean RUT with hyphen, no dots
  pattern: '^[1-9][0-9]{6,7}-[0-9kK]$'
  maxLength: 10
  example: 12345678-5

Pick hyphen or dotted for a contract, not any. Naming one shape tells clients exactly what to send, and it avoids a trap covered below: the compact shape is just nine characters of digits.

In zod#

In a zod schema the pattern and the validator do different jobs. The regex is what survives when the schema is exported to JSON Schema for documentation. The refinement is what actually decides.

TypeScript
import { z } from "zod";
import { RUT_PATTERN, isValidRut } from "rut.ts";
import type { Rut } from "rut.ts";
 
export const rutField = z
  .string()
  .trim()
  .regex(new RegExp(RUT_PATTERN.hyphen), "Use the format 12345678-5")
  .refine((v): v is Rut => isValidRut(v, { strict: true }), {
    message: "Enter a valid Chilean RUT",
  });

The two error messages are worth keeping apart. A shape failure means the user typed the wrong format and can be told which one to use. A verifier failure means a digit is wrong, and the format hint would only confuse them.

In the database#

A constraint is the last line of defense, because it holds no matter what wrote the row: your service, a migration script, or someone with a SQL console. If you store the cleaned form recommended in the database guide — digits plus verifier, no punctuation — use compact:

sql
ALTER TABLE customers
  ADD CONSTRAINT customers_rut_shape
  CHECK (rut ~ '^[1-9][0-9]{6,7}[0-9kK]$');

The example uses PostgreSQL's ~ operator. Because the pattern has no backslashes there is nothing to double inside the SQL string literal. One detail to keep in mind: the patterns accept both k and K, as validate() does. clean() always writes the verifier in uppercase, so keep normalizing on write and the column stays consistent.

In another language#

The same string works unchanged in other regex engines, with one thing to watch: how each engine reads ^ and $.

python
import re
 
RUT_HYPHEN = r"^[1-9][0-9]{6,7}-[0-9kK]$"
 
def looks_like_rut(value: str) -> bool:
    return re.fullmatch(RUT_HYPHEN, value) is not None
go
var rutHyphen = regexp.MustCompile(`^[1-9][0-9]{6,7}-[0-9kK]$`)
 
func looksLikeRut(value string) bool {
	return rutHyphen.MatchString(value)
}
  • Python: use re.fullmatch. With re.search, $ also matches just before a trailing newline, so "12345678-5\n" would pass.
  • Perl: same as Python's re.search; $ allows a trailing newline.
  • Ruby: ^ and $ are line anchors, so a multi-line string with a RUT on one of its lines matches. Replace them with \A and \z.
  • Go and SQLite give the same result as JavaScript.

We ran the same 46,000-string corpus through each of these engines to check this, so the notes above are measurements, not guesses.

Since rut.ts 5.1.2, the library's notes also cover Java (find()), .NET, PHP/PCRE and MySQL 8 (REGEXP_LIKE, which uses ICU). In all of them $ also matches before a final line break, so replace it with \z there (\\z inside a MySQL string literal). The RUT_PATTERN reference has the full list.

What a pattern cannot do#

A regex cannot do arithmetic, and the verifier digit is arithmetic. That limit has a size, and it is larger than most people expect:

  • About ten in eleven strings that match are not real RUTs. There are eleven possible verifiers and only one is right for a given body.
  • A pattern catches almost no typos. Changing one digit of a valid RUT leaves its shape intact. In a test of 300,000 single-digit typos, the pattern caught 1.4% of them; validate() caught every one.
  • compact and any match phone numbers. Every 9-digit Chilean mobile number has the compact shape, and about one in eleven of them even passes validate(). A field that might receive either needs the hyphen or dotted shape to tell them apart.

So the division of labor is the one from Why regex alone can't validate a Chilean RUT: the pattern is a shape filter for places that can only run a regex, and validate() is the decision wherever code can run.

WhereWhat runs thereWhat it guarantees
API schemaRUT_PATTERN.hyphenThe format is documented and malformed input is rejected early
Form and service codevalidate() / isValidRut()The RUT is real: shape and verifier
DatabaseRUT_PATTERN.compact in a CHECKNothing malformed is stored, whatever wrote it

Pitfalls#

Treating a pattern match as validation. If a value reaches a place where code can run, run validate() there. A schema-only check will accept 12345678-0, which has the right shape and the wrong verifier.

Using any in a contract. It accepts three spellings of the same RUT, so clients will send all three and your storage layer will have to normalize them anyway. Choose one shape and document it.

Copying the string once and forgetting it. A pasted string cannot update itself. Where the consumer is TypeScript, import RUT_PATTERN rather than pasting its value. The four strings are part of the library's frozen contract, so a pasted copy stays correct, but an import makes that visible.

Forgetting trim(). validate() and isRutLike() ignore surrounding whitespace; a regex does not. Trim before matching, or the pattern rejects input the validator would accept.

Further reading#

rut.ts

MIT License © 2026 Arrow Software