--- url: /en/integrations/backend.md --- # Express & Hono RUT validation in backend APIs. Both frameworks follow similar patterns. ::: code-group ```bash [npm] npm install rut-kit zod ``` ```bash [pnpm] pnpm add rut-kit zod ``` ```bash [bun] bun add rut-kit zod ``` ::: ## Express Validate the request body using the Zod schema. Errors are returned with status 400. ```typescript import express from 'express' import { z } from 'zod' import { rutSchema } from 'rut-kit/zod' const app = express() app.use(express.json()) const schema = z.object({ rut: rutSchema }) app.post('/api/users', (req, res) => { const result = schema.safeParse(req.body) if (!result.success) { return res.status(400).json({ error: result.error.flatten() }) } // result.data.rut is already validated: '18972631-7' res.json({ success: true }) }) ``` ## Hono Hono has an official Zod validator that simplifies the code. Validation happens automatically before reaching the handler. ```typescript import { Hono } from 'hono' import { z } from 'zod' import { rutSchema } from 'rut-kit/zod' import { zValidator } from '@hono/zod-validator' const app = new Hono() const schema = z.object({ rut: rutSchema }) app.post('/api/users', zValidator('json', schema), (c) => { const data = c.req.valid('json') // data.rut: '18972631-7' return c.json({ success: true }) }) ``` If validation fails, Hono automatically returns a 400 error with the details. ## Without Zod If you prefer not to use Zod, you can validate directly with the core functions: ```typescript import { validateRut } from 'rut-kit' app.post('/api/users', (req, res) => { const result = validateRut(req.body.rut) if (!result.valid) { return res.status(400).json({ error: result.error }) } // result.rut: '189726317' res.json({ success: true }) }) ``` In this case, `result.error` contains the error type (`'invalidFormat'` or `'invalidCheckDigit'`) that you can use to build your own response. --- --- url: /en/guide/llms.md --- # For AI Assistants If you use AI assistants like Claude, ChatGPT, or Cursor, you can provide them with the full documentation context using these files: * [llms.txt](/llms.txt) - Documentation index with links to all pages * [llms-full.txt](/llms-full.txt) - Complete documentation in a single file ## Usage Copy the URL and paste it into your AI assistant's context, or ask it to fetch the content: ``` https://rut-kit.pages.dev/llms-full.txt ``` This helps the AI understand the full API and provide more accurate code examples. --- --- url: /en/guide/formatting.md --- # Formatting Chilean RUTs are written in various ways. rut-kit lets you normalize any input to the format you need. ## Which format to use? | Format | Example | When to use | |--------|---------|-------------| | Default | `18972631-7` | Store in database | | Formatted | `18.972.631-7` | Display to user | | Clean | `189726317` | Comparisons, external APIs | ## Format for display ```typescript import { formatRut } from 'rut-kit' const rut = '189726317' formatRut(rut, 'formatted') // '18.972.631-7' ``` ## Format for storage ```typescript formatRut('18.972.631-7') // '18972631-7' (default) ``` ## Clean dirty data If you have RUTs from Excel, PDFs, or other sources with unusual separators: ```typescript import { cleanRut } from 'rut-kit' cleanRut('18,972,631-7') // '189726317' cleanRut('18*972*631*7') // '189726317' cleanRut('33.333.335-k') // '33333335K' ``` ::: tip `cleanRut()` is permissive: it removes any character that isn't a digit or K. Ideal for normalizing data before validation. ::: ## Calculate check digit For generating RUTs in tests: ```typescript import { getRutCheckDigit } from 'rut-kit' getRutCheckDigit('18972631') // '7' getRutCheckDigit('33333335') // 'K' ``` *** See full reference at [API rut-kit](/en/api/rut-kit) --- --- url: /en/guide/getting-started.md --- # Getting Started rut-kit validates Chilean RUTs with descriptive errors. Instead of just `true/false`, it tells you exactly what failed. ## Installation ::: code-group ```bash [npm] npm install rut-kit ``` ```bash [pnpm] pnpm add rut-kit ``` ```bash [bun] bun add rut-kit ``` ::: ## Validate a RUT ```typescript import { validateRut } from 'rut-kit' const result = validateRut('18.972.631-7') if (result.valid) { console.log(result.rut) // '189726317' } else { console.log(result.error) // 'invalidFormat' or 'invalidCheckDigit' } ``` ## Format a RUT ```typescript import { formatRut } from 'rut-kit' formatRut('189726317') // '18972631-7' formatRut('189726317', 'formatted') // '18.972.631-7' ``` ## With Zod If you use Zod for form validation: ```bash npm install rut-kit zod ``` ```typescript import { rutSchema } from 'rut-kit/zod' rutSchema.parse('18.972.631-7') // '18972631-7' ``` ::: warning Framework Agnostic **rut-kit** works with any JavaScript framework. The integration examples are for frameworks we've tested, but you can use it with Vue, Svelte, Angular, etc. in the same way. ::: ## Next Steps * [Validation](/en/guide/validation) - When to use `isValidRut` vs `validateRut` * [Formatting](/en/guide/formatting) - Output formats and data cleaning * [Zod](/en/guide/zod) - Schema for forms and APIs --- --- url: /en/integrations/nextjs.md --- # Next.js RUT validation in Server Actions and API Routes using the App Router. ::: code-group ```bash [npm] npm install rut-kit zod ``` ```bash [pnpm] pnpm add rut-kit zod ``` ```bash [bun] bun add rut-kit zod ``` ::: ## Server Action Server Actions allow you to validate forms directly on the server. The Zod schema validates and formats the RUT before processing. ```typescript 'use server' import { z } from 'zod' import { rutSchema } from 'rut-kit/zod' const schema = z.object({ rut: rutSchema }) export async function action(formData: FormData) { const result = schema.safeParse({ rut: formData.get('rut') }) if (!result.success) { return { error: result.error.flatten() } } // result.data.rut is already validated and formatted // '18972631-7' } ``` Use `safeParse` to handle errors without throwing exceptions. The `flatten()` method converts Zod errors into a format that's easier to consume on the client. ## API Route For REST endpoints, the pattern is similar. Validate the request body and return errors with the appropriate status code. ```typescript import { NextRequest, NextResponse } from 'next/server' import { z } from 'zod' import { rutSchema } from 'rut-kit/zod' const schema = z.object({ rut: rutSchema }) export async function POST(request: NextRequest) { const body = await request.json() const result = schema.safeParse(body) if (!result.success) { return NextResponse.json( { error: result.error.flatten() }, { status: 400 } ) } // result.data.rut: '18972631-7' return NextResponse.json({ success: true }) } ``` The RUT in `result.data.rut` is already validated and formatted, ready to save to the database. --- --- url: /en/integrations/react.md --- # React ::: warning Framework Agnostic **rut-kit** works with any JavaScript framework. These examples are for frameworks we've tested, but you can use it with Vue, Svelte, Angular, etc. in the same way. ::: RUT validation in React using rut-kit's core functions. Ideal for simple forms without needing additional validation libraries. ::: code-group ```bash [npm] npm install rut-kit ``` ```bash [pnpm] pnpm add rut-kit ``` ```bash [bun] bun add rut-kit ``` ::: ## Validation with onBlur Validates when the user leaves the field, without interrupting while typing: ```tsx import { useState } from 'react' import { getErrorMessage, validateRut } from 'rut-kit' function Form() { const [rut, setRut] = useState('') const [error, setError] = useState(null) const handleBlur = (e: React.FocusEvent) => { const result = validateRut(e.target.value) setError(result.valid ? null : getErrorMessage(result.error)) } const handleSubmit = (e: React.FormEvent) => { e.preventDefault() const result = validateRut(rut) if (result.valid) { console.log({ rut: result.rut }) } else { setError(getErrorMessage(result.error)) } } return (
{ setRut(e.target.value) setError(null) }} onBlur={handleBlur} /> {error && {error}}
) } ``` **Features:** * Validates when user leaves the field * Doesn't interrupt while user is typing * Better UX for simple forms * Uses `validateRut()` and `getErrorMessage()` ## Auto Formatting Formats the RUT in real-time as the user types: ```tsx import { useState } from 'react' import { formatRut, getErrorMessage, validateRut } from 'rut-kit' function Form() { const [rut, setRut] = useState('') const [error, setError] = useState(null) const handleChange = (e: React.ChangeEvent) => { const formatted = formatRut(e.target.value, 'formatted') setRut(formatted) setError(null) } const handleSubmit = (e: React.FormEvent) => { e.preventDefault() const result = validateRut(rut) if (result.valid) { console.log({ rut }) } else { setError(getErrorMessage(result.error)) } } return (
{error && {error}}
) } ``` **Features:** * Real-time formatting with `formatRut()` * Immediate visual feedback * Validates on submit * Always consistent format ::: tip Auto formatting improves user experience by showing the correct format as they type, but only validates on submit to not interrupt the typing flow. ::: ## When to use React without libraries? * Simple forms that don't need React Hook Form * When you want full control over the validation flow * Projects that don't require complex validation schemas * For real-time validation (onChange, onBlur) ::: info If you need more complex form validation, consider using [React Hook Form + Zod](/en/integrations/react-hook-form). ::: --- --- url: /en/integrations/react-hook-form.md --- # React Hook Form + Zod Integration with React Hook Form using the Zod schema for automatic validation. ::: code-group ```bash [npm] npm install rut-kit zod react-hook-form @hookform/resolvers ``` ```bash [pnpm] pnpm add rut-kit zod react-hook-form @hookform/resolvers ``` ```bash [bun] bun add rut-kit zod react-hook-form @hookform/resolvers ``` ::: ## Basic Validation The simplest way to integrate rut-kit with React Hook Form is using the Zod resolver. The schema validates automatically and error messages appear in `errors`. ```tsx import { useForm } from 'react-hook-form' import { zodResolver } from '@hookform/resolvers/zod' import { z } from 'zod' import { rutSchema } from 'rut-kit/zod' const schema = z.object({ rut: rutSchema }) function Form() { const { register, handleSubmit, formState: { errors } } = useForm({ resolver: zodResolver(schema), mode: 'onSubmit', reValidateMode: 'onSubmit', defaultValues: { rut: '' } }) return (
{errors.rut && {errors.rut.message}}
) } ``` When the form submits successfully, `data.rut` is already formatted and validated. ::: tip Use `rutSchema` with `reValidateMode: 'onSubmit'` to avoid premature errors while the user is typing. If the field is required, validate it on `onSubmit` or use a wrapper schema. ::: ## Real-Time Validation If you want the input to show the formatted RUT while the user types, there are two main approaches: ### Destructuring onChange Extract the `onChange` from `register` and combine it with `formatRut`: ```tsx import { useForm } from 'react-hook-form' import { zodResolver } from '@hookform/resolvers/zod' import { z } from 'zod' import { rutSchema } from 'rut-kit/zod' import { formatRut } from 'rut-kit' const schema = z.object({ rut: rutSchema }) function Form() { const { register, handleSubmit, setValue, formState: { errors } } = useForm({ resolver: zodResolver(schema), mode: 'onSubmit', reValidateMode: 'onSubmit', defaultValues: { rut: '' } }) const { onChange, ...rest } = register('rut') return (
{ const formatted = formatRut(e.target.value, 'formatted') setValue('rut', formatted, { shouldValidate: false }) await onChange(e) }} /> {errors.rut && {errors.rut.message}}
) } ``` **Features:** * More direct with less code * Perfect for simple transformations * You must call `onChange(e)` manually to maintain React Hook Form's state ### Controller Use React Hook Form's `Controller` component for more control: ```tsx import { useForm, Controller } from 'react-hook-form' import { zodResolver } from '@hookform/resolvers/zod' import { z } from 'zod' import { rutSchema } from 'rut-kit/zod' import { formatRut } from 'rut-kit' const schema = z.object({ rut: rutSchema }) function Form() { const { control, handleSubmit, formState: { errors } } = useForm({ resolver: zodResolver(schema), mode: 'onSubmit', reValidateMode: 'onSubmit', defaultValues: { rut: '' } }) return (
( { const formatted = formatRut(e.target.value, 'formatted') field.onChange(formatted) }} /> )} /> {errors.rut && {errors.rut.message}} ) } ``` **Features:** * Official React Hook Form approach * Greater control over field behavior * Better for integrating with third-party UI libraries (Material UI, Base UI, etc.) * `field.onChange()` automatically handles internal state ::: tip Use `formatRut(value, 'formatted')` to show the RUT with dots and dash (`12.345.678-9`) while the user types. The Zod schema will normalize the format when submitting the form. ::: --- --- url: /en/api/rut-kit.md --- # rut-kit Core API reference for validating, formatting, and working with Chilean RUTs. ```typescript import { isValidRut, validateRut, formatRut, cleanRut, getRutCheckDigit, getErrorMessage } from 'rut-kit' ``` ## isValidRut Validates if a Chilean RUT is valid. ```typescript function isValidRut(rut: string): boolean ``` ### Parameters | Name | Type | Description | |------|------|-------------| | `rut` | `string` | RUT to validate | ### Return `boolean` - `true` if the RUT is valid, `false` otherwise. ### Accepted Formats * With dots and dash: `18.972.631-7` * Dash only: `18972631-7` * No formatting: `189726317` ::: warning Only accepts valid Chilean formats. Other separators (commas, asterisks) are rejected. Minimum RUT: 1.000.000. ::: ### Example ```typescript isValidRut('18.972.631-7') // true isValidRut('18.972.631-0') // false isValidRut('18,972,631-7') // false ``` *** ## validateRut Validates a RUT and returns detailed information about the result. ```typescript function validateRut(rut: string): RutValidationResult ``` ### Parameters | Name | Type | Description | |------|------|-------------| | `rut` | `string` | RUT to validate | ### Return `RutValidationResult` - Object with the validation result: ```typescript // If valid { valid: true, rut: string } // If invalid { valid: false, error: RutValidationError } ``` ### Error Types | Error | Description | |-------|-------------| | `invalidFormat` | Invalid format, incorrect length, or disallowed characters | | `invalidCheckDigit` | The check digit doesn't match | ### Example ```typescript validateRut('18.972.631-7') // { valid: true, rut: '189726317' } validateRut('18.972.631-0') // { valid: false, error: 'invalidCheckDigit' } validateRut('18,972,631-7') // { valid: false, error: 'invalidFormat' } ``` *** ## formatRut Formats a RUT to the specified format. ```typescript function formatRut(rut: string, format?: RutOutputFormat): string ``` ### Parameters | Name | Type | Description | |------|------|-------------| | `rut` | `string` | RUT to format | | `format` | `RutOutputFormat` | Output format (optional) | ### Output Formats | Format | Result | Recommended Use | |--------|--------|-----------------| | `undefined` (default) | `18972631-7` | Storage | | `'formatted'` | `18.972.631-7` | Display to user | | `'clean'` | `189726317` | Comparisons, APIs | ### Return `string` - Formatted RUT. ### Example ```typescript formatRut('189726317') // '18972631-7' formatRut('189726317', 'formatted') // '18.972.631-7' formatRut('189726317', 'clean') // '189726317' ``` ::: tip This function is permissive: it accepts any input separator. It uses `cleanRut()` internally. ::: *** ## cleanRut Extracts only digits and the letter K from a RUT, removing any other character. ```typescript function cleanRut(rut: string): string ``` ### Parameters | Name | Type | Description | |------|------|-------------| | `rut` | `string` | RUT to clean | ### Return `string` - Clean RUT (only digits and uppercase K). Removes leading zeros. ### Example ```typescript cleanRut('18.972.631-7') // '189726317' cleanRut('33.333.335-k') // '33333335K' cleanRut('18,972,631-7') // '189726317' cleanRut('18*972*631*7') // '189726317' ``` ::: tip Permissive function. Useful for cleaning data from Excel, PDFs, or other sources with non-standard separators. ::: *** ## getRutCheckDigit Calculates the check digit of a RUT using the modulo 11 algorithm. ```typescript function getRutCheckDigit(rut: string): string ``` ### Parameters | Name | Type | Description | |------|------|-------------| | `rut` | `string` | RUT body (without check digit) | ### Return `string` - Calculated check digit (`'0'`-`'9'` or `'K'`). ### Example ```typescript getRutCheckDigit('18972631') // '7' getRutCheckDigit('33333335') // 'K' getRutCheckDigit('11111111') // '1' ``` *** ## getErrorMessage Converts an error type to a human-readable message. ```typescript function getErrorMessage(error: RutValidationError, messages?: RutErrorMessages): string ``` ### Parameters | Name | Type | Description | |------|------|-------------| | `error` | `RutValidationError` | Error type to convert | | `messages` | `RutErrorMessages` | Custom messages (optional) | ### Return `string` - Human-readable error message. ### Default Messages | Error | Message | |-------|---------| | `invalidFormat` | `'Invalid RUT format'` | | `invalidCheckDigit` | `'Invalid check digit'` | ### Example ```typescript const result = validateRut('18.972.631-0') if (!result.valid) { getErrorMessage(result.error) // 'Invalid check digit' getErrorMessage(result.error, { invalidCheckDigit: 'RUT is not valid' }) // 'RUT is not valid' } ``` --- --- url: /en/api/rut-kit-zod.md --- # rut-kit/zod Zod API reference for validating RUTs in forms and APIs. ```typescript import { rutSchema, createRutSchema } from 'rut-kit/zod' ``` ::: info Requirement Requires `zod` as a peer dependency: `npm install rut-kit zod` ::: ## rutSchema Pre-configured Zod schema for validating Chilean RUTs. ```typescript const rutSchema: ZodEffects ``` ### Behavior 1. Validates that it's not empty 2. Validates valid Chilean format (`18.972.631-7`, `18972631-7`, `189726317`) 3. Validates the check digit 4. Returns the normalized RUT (no dots, with dash) ### Example ```typescript rutSchema.parse('18.972.631-7') // '18972631-7' rutSchema.parse('189726317') // '18972631-7' rutSchema.safeParse('18.972.631-0') // { success: false, error: ZodError } // error.issues[0].message: 'Invalid check digit' ``` ### Error Messages | Case | Message | |------|---------| | Empty | `'RUT is required'` | | Invalid format | `'Invalid RUT format'` | | Invalid check digit | `'Invalid check digit'` | *** ## createRutSchema Creates a custom schema with custom messages or output format. ```typescript function createRutSchema(options?: RutSchemaOptions): ZodEffects ``` ### Parameters | Name | Type | Description | |------|------|-------------| | `options` | `RutSchemaOptions` | Configuration options (optional) | ### RutSchemaOptions | Option | Type | Description | |--------|------|-------------| | `messages` | `RutErrorMessages` | Custom error messages | | `outputFormat` | `'formatted'` | `'clean'` | Format of the returned RUT | ### Output Formats | Format | Result | |--------|--------| | `undefined` (default) | `18972631-7` | | `'formatted'` | `18.972.631-7` | | `'clean'` | `189726317` | ### Example ```typescript // Custom messages const schema = createRutSchema({ messages: { required: 'Enter your RUT', invalidFormat: 'Incorrect format', invalidCheckDigit: 'Invalid digit' } }) // Output format const displaySchema = createRutSchema({ outputFormat: 'formatted' }) displaySchema.parse('189726317') // '18.972.631-7' // Combining options const customSchema = createRutSchema({ messages: { required: 'RUT required' }, outputFormat: 'formatted' }) ``` *** ## Usage with Zod Objects ```typescript import { z } from 'zod' import { rutSchema } from 'rut-kit/zod' const userSchema = z.object({ name: z.string().min(1), rut: rutSchema, email: z.string().email() }) userSchema.parse({ name: 'Juan', rut: '18.972.631-7', email: 'juan@example.cl' }) // { name: 'Juan', rut: '18972631-7', email: 'juan@example.cl' } ``` --- --- url: /en/guide/validation.md --- # Validation rut-kit offers two ways to validate RUTs depending on what you need to know. ## Just need to know if it's valid? Use `isValidRut`: ```typescript import { isValidRut } from 'rut-kit' if (isValidRut(input)) { // Valid RUT } ``` ## Need to know what failed? Use `validateRut` + `getErrorMessage`: ```typescript import { validateRut, getErrorMessage } from 'rut-kit' const result = validateRut(input) if (result.valid) { console.log(result.rut) // Clean RUT: '189726317' } else { console.log(getErrorMessage(result.error)) // 'Invalid RUT format' or 'Invalid check digit' } ``` ## Have data with unusual separators? If you receive RUTs from Excel, PDFs, or other sources with commas or asterisks, clean first: ```typescript import { cleanRut, validateRut } from 'rut-kit' const dirty = '18,972,631-7' const clean = cleanRut(dirty) // '189726317' validateRut(clean) // { valid: true, rut: '189726317' } ``` ::: tip Permissive vs Strict * `cleanRut()` is **permissive**: accepts any separator * `validateRut()` is **strict**: only valid Chilean formats Recommended flow for dirty data: `cleanRut()` -> `validateRut()` ::: ## Custom Messages You can change the error messages: ```typescript getErrorMessage(result.error, { invalidFormat: 'Check the RUT format', invalidCheckDigit: 'The RUT is not valid' }) ``` *** See full reference at [API rut-kit](/en/api/rut-kit) --- --- url: /en/guide/zod.md --- # Zod rut-kit includes a ready-to-use Zod schema for forms and APIs. ## Installation ```bash npm install rut-kit zod ``` ## Basic Usage ```typescript import { rutSchema } from 'rut-kit/zod' rutSchema.parse('18.972.631-7') // '18972631-7' ``` The schema validates format and check digit, and returns the normalized RUT. ## In Forms ```typescript import { z } from 'zod' import { rutSchema } from 'rut-kit/zod' const formSchema = z.object({ name: z.string().min(1), rut: rutSchema, email: z.string().email() }) ``` ## Handle Errors ```typescript const result = rutSchema.safeParse(input) if (!result.success) { console.log(result.error.issues[0].message) // 'Invalid RUT format' or 'Invalid check digit' } ``` ## Custom Messages ```typescript import { createRutSchema } from 'rut-kit/zod' const schema = createRutSchema({ messages: { required: 'Enter your RUT', invalidFormat: 'Incorrect format', invalidCheckDigit: 'Invalid RUT' } }) ``` ## Change Output Format ```typescript // For user display const displaySchema = createRutSchema({ outputFormat: 'formatted' }) displaySchema.parse('189726317') // '18.972.631-7' // For APIs that require only numbers const apiSchema = createRutSchema({ outputFormat: 'clean' }) apiSchema.parse('18.972.631-7') // '189726317' ``` *** See full reference at [API rut-kit/zod](/en/api/rut-kit-zod)