PHPackages                             cdmckay/pajama - 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. cdmckay/pajama

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

cdmckay/pajama
==============

A PHP model validator compatible with the jQuery Validation plugin that allows for shared validation rules (in JSON) between JavaScript and PHP.

152784[1 issues](https://github.com/cdmckay/pajama/issues)PHP

Since Jul 17Pushed 12y ago5 watchersCompare

[ Source](https://github.com/cdmckay/pajama)[ Packagist](https://packagist.org/packages/cdmckay/pajama)[ RSS](/packages/cdmckay-pajama/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

Pajama
======

[](#pajama)

Pajama provides drop-in server-side validation for your existing [jQuery Validation plugin](http://bassistance.de/jquery-plugins/jquery-plugin-validation/) forms. It can also be used for standalone server-side validation in a pinch.

Since the goal of Pajama was to be used with the jQuery Validation plugin, the API has been designed to be similar and thus familiar to developers who already know how to use the jQuery Validation plugin.

For more information on using the Pajama API, please [refer to the documentation](http://cdmckay.org/pajama/docs/namespaces/Pajama.html).

For documentation on the validation methods (like required, min, max, etc.) refer to the [jQuery Validation plugin documentation](http://docs.jquery.com/Plugins/Validation#List_of_built-in_Validation_methods).

Pajama is now [Composer](http://getcomposer.org/)-compatible and available on [Packagist](https://packagist.org/packages/cdmckay/pajama). Simply add this line to your `composer.json` to use it:

```
{
    "require": {
        ...
        "cdmckay/pajama": "dev-master"
    }
}
```

Getting Started (jQuery Validation integration)
-----------------------------------------------

[](#getting-started-jquery-validation-integration)

First, get [jQuery](http://code.jquery.com/jquery-latest.js) and the [jQuery Validation plugin](http://bassistance.de/jquery-plugins/jquery-plugin-validation/).

Next, create a `rules.json` file:

```
{
    "rating":{
        "required":true,
        "range":[1, 100]
    }
}
```

Now, include jQuery and the jQuery Validation plugin on a page:

```

        Getting Started

            Rating:

        $.getJSON("rules.json", function(rules) {
            $("form").validate({ rules: rules });
        });

```

Finally, create a PHP script to handle the form submission:

```
require 'ValidatorContext.php';
require 'Validator.php';

\Cdmckay\Pajama\Validator::validate(array(
    'model' => $_POST,
    'rules' => json_decode('rules.json', true),
    'validHandler' => function() {
        // Store rating in database.
    },
));
```

For a more detailed example, see the `jquery-validation-integration` example in the `examples` folder.

Getting Started (standalone)
----------------------------

[](#getting-started-standalone)

Although not its primary design goal, Pajama can be used standalone. Simply include the `vendor/autoload.php` file (generated by Composer) in your PHP script and pass it a model and some rules, like so:

```
$rules = array(
    'first_name' => 'required',
    'last_name' => 'required',
    'password_1' => array(
        'required' => true,
        'minlength' => 5,
        'equalTo' => '#password_2',
    ),
    'password_2' => array(
        'required' => true,
        'minlength' => 5,
        'equalTo' => '#password_1',
    ),
);

// Validate with callbacks...
$validator = \Cdmckay\Pajama\Validator::validate(array(
    'model' => $_POST,
    'rules' => $rules,
    'validHandler' => function() {
        // Model validated.
    },
    'invalidHandler' => function() {
        // Model failed validation.
    },
));

// ...or methods.
if($validator->model()) {
    // Model validated.
} else {
    // Model failed validation.
}
```

See the `standalone` example in the `examples` folder.

Custom Validators
-----------------

[](#custom-validators)

Like the jQuery Validation plugin, Pajama can be extended via custom validators. To create a custom validator, use the [addMethod](http://cdmckay.org/pajama/docs/classes/Pajama.Validator.html#method_addMethod) static method like so:

```
\Cdmckay\Pajama\Validator::addMethod('regex', function($context, $value, $param)) {
    return $context->optional($value) || preg_match('/' . $param . '/', $value);
});

\Cdmckay\Pajama\Validator::validate(array(
    'model' => $_POST,
    'rules' => array(
        'md5_hash' => array(
            'required' => true,
            'regex' => '^[A-Fa-f0-9]+$',
        ),
    ),
    'validHandler' => function() {
        // ...
    },
));
```

Remember that if you're using Pajama with the jQuery Validation plugin, you must also write a JavaScript version of the validation method:

```
$.validator.addMethod("regex", function(value, element, param) {
    return this.optional(element) || new RegExp(param).test(value);
}, "This field does not conform to a pattern.");
```

Limitations
-----------

[](#limitations)

Since Pajama has no access to the submitting form's DOM context, it only has limited support for CSS selectors.

For example, consider this mark-up:

```

        Bar
        Baz

```

The jQuery Validation plugin [required](http://docs.jquery.com/Plugins/Validation/Methods/required)validation method can support arbitrary jQuery selectors like this:

```
{
    "email": {
        "required":".checkbox-group :checkbox:first:checked"
        "email":true
    }
}
```

However, the best Pajama can do is this:

```
{
    "email": {
        "required":"[name=foo[0]]:checked"
        "email":true
    }
}
```

In general, Pajama can only recognize selectors with the form `#foo` or `[name=foo]` and the following pseudo-classes:

- `:checked`
- `:unchecked`
- `:filled`
- `:blank`

In the case of `#foo`, Pajama assumes that the `name` and the `id` of the element were the same, as in:

```

```

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance19

Infrequent updates — may be unmaintained

Popularity23

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity41

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.

### Community

Maintainers

![](https://www.gravatar.com/avatar/35ba8822bd5f41658564b2e048844b5bac44499d33dfc2a81ce313b25fe7e3c8?d=identicon)[cdmckay](/maintainers/cdmckay)

---

Top Contributors

[![cdmckay](https://avatars.githubusercontent.com/u/67923?v=4)](https://github.com/cdmckay "cdmckay (37 commits)")

### Embed Badge

![Health badge](/badges/cdmckay-pajama/health.svg)

```
[![Health](https://phpackages.com/badges/cdmckay-pajama/health.svg)](https://phpackages.com/packages/cdmckay-pajama)
```

###  Alternatives

[webmozart/assert

Assertions to validate method input/output with nice error messages.

7.6k894.0M1.2k](/packages/webmozart-assert)[bensampo/laravel-enum

Simple, extensible and powerful enumeration implementation for Laravel.

2.0k15.9M104](/packages/bensampo-laravel-enum)[swaggest/json-schema

High definition PHP structures with JSON-schema based validation

48612.5M73](/packages/swaggest-json-schema)[stevebauman/purify

An HTML Purifier / Sanitizer for Laravel

5325.6M19](/packages/stevebauman-purify)[ashallendesign/laravel-config-validator

A package for validating your Laravel app's config.

217905.3k5](/packages/ashallendesign-laravel-config-validator)[crazybooot/base64-validation

Laravel validators for base64 encoded files

1341.9M8](/packages/crazybooot-base64-validation)

PHPackages © 2026

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