PHPackages                             webrek/mx-validation - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. webrek/mx-validation

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

webrek/mx-validation
====================

Validate and generate Mexican identifiers — RFC, CURP, CLABE, NSS and código postal — with real check-digit verification. Framework-agnostic core with an optional Laravel bridge (rules, casts, Faker).

v1.0.0(yesterday)00MITPHPPHP ^8.2CI passing

Since Jun 29Pushed yesterdayCompare

[ Source](https://github.com/webrek/mx-validation)[ Packagist](https://packagist.org/packages/webrek/mx-validation)[ Docs](https://github.com/webrek/mx-validation)[ RSS](/packages/webrek-mx-validation/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (13)Versions (2)Used By (0)

MX Validation
=============

[](#mx-validation)

[![Última versión](https://camo.githubusercontent.com/00d213c014edbd8601e33789e5ec6a7ee0936e69785ed842bd54c9844e52e388/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f762f7461672f77656272656b2f6d782d76616c69646174696f6e3f736f72743d73656d766572266c6162656c3d76657273692543332542336e267374796c653d666c61742d737175617265)](https://github.com/webrek/mx-validation/releases)[![Tests](https://camo.githubusercontent.com/b62401e51e4668105990cfee8f5f71135593c778dfcd158c4979f5b25583d761/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f77656272656b2f6d782d76616c69646174696f6e2f74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/webrek/mx-validation/actions/workflows/tests.yml)[![PHP](https://camo.githubusercontent.com/2195866c8c0e50a0cac338d708a9c7056b9681de027de3ac357d3fd4f93c55a2/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e322d3737376262343f7374796c653d666c61742d737175617265)](https://php.net)[![Licencia](https://camo.githubusercontent.com/59486279cdf27f71eb9d1dff3250ff435e7f8d6d04130ab810a798b8ffb17b2a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f77656272656b2f6d782d76616c69646174696f6e3f7374796c653d666c61742d737175617265)](LICENSE)

Valida y **genera** los identificadores mexicanos que toca cualquier app — **RFC, CURP, CLABE, NSS** y **código postal** — con **verificación real del dígito verificador**, no solo una expresión regular.

Un **núcleo independiente de framework** (solo PHP y [nesbot/carbon](https://github.com/briannesbitt/Carbon)) con un **puente opcional para Laravel**: reglas de validación, *casts* de Eloquent y un proveedor de Faker.

```
use Webrek\MxValidation\ValueObjects\Rfc;

Rfc::isValid('GODE561231GR8');   // true  — estructura + fecha + dígito verificador
Rfc::isValid('GODE561231GR9');   // false — el dígito verificador no coincide
```

Instalación
-----------

[](#instalación)

```
composer require webrek/mx-validation
```

No requiere ningún framework. En Laravel, el *service provider* se descubre solo y registra las reglas y el proveedor de Faker.

Value objects (núcleo, sin framework)
-------------------------------------

[](#value-objects-núcleo-sin-framework)

Cada identificador tiene un value object inmutable con `isValid()`, `tryParse()`(null al fallar) y `parse()` (lanza `InvalidIdentifierException`), más *accessors*:

```
use Webrek\MxValidation\ValueObjects\{Rfc, Curp, Clabe};

$rfc = Rfc::parse('  xaxx-010101-000 ');
$rfc->value;        // "XAXX010101000"  (normalizado)
$rfc->isFisica();   // true
$rfc->isGeneric();  // true  (RFC genérico del SAT)

$curp = Curp::parse('PEPJ900101HDFRRN09');
$curp->sex();            // "H"
$curp->stateName();      // "Ciudad de México"
$curp->birthDate();      // CarbonImmutable 1990-01-01
$curp->isForeignBorn();  // false  (true cuando el código de entidad es "NE")

$clabe = Clabe::parse('002010077777777771');
$clabe->bankName();   // "Banamex"
```

Generar un RFC o CURP a partir de un nombre
-------------------------------------------

[](#generar-un-rfc-o-curp-a-partir-de-un-nombre)

```
use Webrek\MxValidation\ValueObjects\{Rfc, Curp};

Rfc::fromName('Gómez', 'Díaz', 'Emma', '1956-12-31');
// GODE561231GR8  (el propio ejemplo del SAT)

Curp::fromName('Pérez', 'López', 'Juan', '1990-05-15', sex: 'H', state: 'JC');
// PELJ900515HJCRPN03
```

Aplican las reglas del SAT/RENAPO (quita partículas, salta nombre común María/José, filtro de palabras altisonantes) y el algoritmo de homoclave está verificado contra el ejemplo publicado por el SAT.

> **Presuntivo, no autoritativo.** La homoclave del RFC y el diferenciador de la CURP (posición 17) sirven para desempatar homónimos; la autoridad puede asignar otro valor. Trátalo como un buen candidato para precargar un formulario, nunca como sustituto del documento oficial.

En Laravel
----------

[](#en-laravel)

### Reglas de validación

[](#reglas-de-validación)

```
$request->validate([
    'rfc'           => ['required', 'rfc'],
    'curp'          => ['required', 'curp'],
    'clabe'         => ['required', 'clabe'],
    'nss'           => ['required', 'nss'],
    'codigo_postal' => ['required', 'codigo_postal'],
]);
```

…o como objetos de regla:

```
use Webrek\MxValidation\Laravel\Rules;

$request->validate(['rfc' => ['required', new Rules\Rfc]]);
```

Los mensajes de error vienen en español de fábrica y respetan las sustituciones de mensajes personalizados de Laravel.

### Casts de Eloquent

[](#casts-de-eloquent)

```
use Webrek\MxValidation\Laravel\Casts\{RfcCast, CurpCast, ClabeCast, NssCast};

class Taxpayer extends Model
{
    protected $casts = [
        'rfc'   => RfcCast::class,
        'curp'  => CurpCast::class,
        'clabe' => ClabeCast::class,
        'nss'   => NssCast::class,
    ];
}

$taxpayer->rfc = 'xaxx-010101-000';   // se guarda "XAXX010101000"
$taxpayer->rfc->isGeneric();          // true — al leer es una instancia de Rfc
```

Asignar un valor inválido lanza `InvalidIdentifierException`; `null` queda `null`.

Faker
-----

[](#faker)

Un proveedor de Faker genera identificadores válidos (pero ficticios) con dígitos verificadores correctos. En Laravel se registra solo; en otro lado:

```
$faker->addProvider(new \Webrek\MxValidation\Faker\MxProvider($faker));

$faker->rfc();             // persona física
$faker->rfc(moral: true);  // persona moral
$faker->curp();
$faker->clabe();           // o $faker->clabe('012') para fijar el banco
$faker->nss();
```

Qué verifica y qué no
---------------------

[](#qué-verifica-y-qué-no)

Verifica **estructura, la fecha embebida, códigos de entidad/banco válidos y el dígito verificador oficial**. **No** confirma que un valor esté registrado ante el SAT, el IMSS o un banco, y `codigo_postal` es solo un chequeo de formato (la validación completa necesita el catálogo SEPOMEX, que este paquete no incluye). Para generar CFDI, combínalo con [webrek/cfdi](https://github.com/webrek/cfdi).

Pruebas
-------

[](#pruebas)

```
composer test
```

La suite del núcleo (`tests/Unit`) corre sin framework; la de Laravel (`tests/Feature`) ejercita las reglas, los *casts* y el *service provider*.

Contribuir
----------

[](#contribuir)

Consulta [CONTRIBUTING.md](CONTRIBUTING.md). Corre `make check` antes de abrir un *pull request*.

Seguridad
---------

[](#seguridad)

Reporta vulnerabilidades a través del [formulario de avisos de seguridad](https://github.com/webrek/mx-validation/security/advisories/new), no como *issues* públicos. Consulta [SECURITY.md](SECURITY.md).

Licencia
--------

[](#licencia)

Licencia MIT (MIT). Consulta [LICENSE](LICENSE).

###  Health Score

39

—

LowBetter than 85% of packages

Maintenance100

Actively maintained with recent releases

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

1d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/7d8deca81629993819087597b5ad7695976b02e3d014f038e26e985f35f569de?d=identicon)[webrek](/maintainers/webrek)

---

Top Contributors

[![webrek](https://avatars.githubusercontent.com/u/5001338?v=4)](https://github.com/webrek "webrek (2 commits)")

---

Tags

clabecodigo-postalcurplaravelmexiconssphprfcsatvalidationphplaravelvalidationNSSsatmexicorfccurpclabecódigo postal

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/webrek-mx-validation/health.svg)

```
[![Health](https://phpackages.com/badges/webrek-mx-validation/health.svg)](https://phpackages.com/packages/webrek-mx-validation)
```

###  Alternatives

[yorcreative/laravel-argonaut-dto

Argonaut is a lightweight Data Transfer Object (DTO) package for Laravel that supports nested casting, recursive serialization, and validation out of the box. Ideal for service layers, APIs, and clean architecture workflows.

1063.3k2](/packages/yorcreative-laravel-argonaut-dto)[reducktion/socrates

A package to validate, and extract citizen information from, national identification numbers.

478.8k](/packages/reducktion-socrates)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
