PHPackages                             filippo-toso/validate-function - 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. filippo-toso/validate-function

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

filippo-toso/validate-function
==============================

A simple function that helps validating input for use in API development.

v1.1.1(4y ago)0148MITPHPPHP ^7.1.3 || ^8.0 || ^9.0

Since Sep 14Pushed 4y agoCompare

[ Source](https://github.com/filippotoso/validation-function)[ Packagist](https://packagist.org/packages/filippo-toso/validate-function)[ RSS](/packages/filippo-toso-validate-function/feed)WikiDiscussions master Synced 4w ago

READMEChangelogDependencies (3)Versions (8)Used By (0)

Validation Function
===================

[](#validation-function)

A simple function that helps validating inputs for use in API development.

Requirements
------------

[](#requirements)

- PHP 7.1.3+
- Illumintate HTTP 5.5+
- Illumintate Support 5.5+

Installing
----------

[](#installing)

Use Composer to install it:

```
composer require filippo-toso/validate-function

```

Function Signature
------------------

[](#function-signature)

Here is the signature of the validate() function:

```
/**
 * Validate inputs for use in API development
 * @method validate
 * @param  array          $rules              Laravel's style validation rules.
 * @param  null|callable  $successCallback    If it's a callable, $successCallback is called with the validated data as parameter.
 *                                            Otherwise, the validated data is returned by validate().
 * @param  null|callable  $failsCallback      If it's a callable, $failsCallback is called with the validator instance as parameter.
 *                                            Otherwise, it checks if the Dingo API development framework is installed.
 *                                            If it's installed, the function throws a ResourceException with the validation errors.
 *                                            Otherwise it returns a Json response with 422 status code and validation errors as payload.
 * @param  array          $messages           The validation messages.
 * @param  mixed          $input              If it's null, request() will be used instead.
 *                                            Otherwise, you can pass a Request object or an array.
 *                                            In any other case, the function throws an exception for invalid input.
 * @return mixed  The function can return: the result of $successCallback(), the result of $failsCallback,
 *                the validated data or a Json response with the validated errors.
 */

function validate(array $rules, callable $successCallback = null, callable $failsCallback = null, $messages = [], $input = null)

```

Using It
--------

[](#using-it)

Here is the simples example:

```
use function FilippoToso\Validator\validate;
use App\User;
use Illuminate\Http\JsonResponse;

Route::get('/users/search', function() {

    // Call validate() passing only the rules in the first parameter.

    $data = validate([
        'name' => 'nullable|string',
        'email' => 'nullable|string',
        'orderBy' => 'required|in:username,email',
    ]);

    // Validation error
    if (!is_array($data)) {
        return $data;
    }

    // Then use the validated data to get the required response

    $query = User::select('*');

    if (isset($data['name'])) {
        $query->where('name', '=', $data['name']);
    }

    if (isset($data['email'])) {
        $query->where('email', '=', $data['email']);
    }

    $query->orderBy($data['orderBy']);

    return $query->get()->toArray();

});

```

If you prefer, you can achieve the same result using the callable in the second parameter:

```
use function FilippoToso\Validator\validate;
use App\User;

Route::get('/users/search', function() {

    // Call validate() passing the rules in the first parameter and the $successCallback as second.

    return validate([
        'name' => 'nullable|string',
        'email' => 'nullable|string',
        'orderBy' => 'required|in:username,email',
    ], function ($data) {

        // Use the validated data to get the required response.

        $query = User::select('*');

        if (isset($data['name'])) {
            $query->where('name', '=', $data['name']);
        }

        if (isset($data['email'])) {
            $query->where('email', '=', $data['email']);
        }

        $query->orderBy($data['orderBy']);

        // The return of this closure will be the validate() return value.

        return $query->get()->toArray();

    });

});

```

The third parameter is also a callback that it's called if the validator fails. In this case the instance of the validator is passed as parameter. You can use it, for instance, to generate a custom error payload:

```
use function FilippoToso\Validator\validate;
use App\User;

Route::get('/users/search', function() {

    // Call validate() passing the rules in the first parameter and the $successCallback as second.

    return validate([
        'name' => 'nullable|string',
        'email' => 'nullable|string',
        'orderBy' => 'required|in:username,email',
    ], function ($data) {

        // Use the validated data to get the required response.

        $query = User::select('*');

        if (isset($data['name'])) {
            $query->where('name', '=', $data['name']);
        }

        if (isset($data['email'])) {
            $query->where('email', '=', $data['email']);
        }

        $query->orderBy($data['orderBy']);

        // The return of this closure will be the validate() return value.

        return $query->get()->toArray();

    }, function ($validator) {

        // This is exactly what happens if you pass null as $failsCallback and
        // the Dingo framework is not installed.

        return response()->json([
            'message' =>'Faild validation.',
            'status_code' => 422,
            'errors' => $validator->errors(),
        ], 422);

    });

});

```

The forth parameter contains the validator's messages (like the third parameter in Validator::make() or the controller's messages() method).

The last parameter can contain null, a Request object or an array. In the first case the current request() will be used otherwise the content passed will be validated. If the input parameter doesn't contain a valid value, an exception will be thrown.

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity10

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity84

Battle-tested with a long release history

 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

Every ~185 days

Recently: every ~273 days

Total

7

Last Release

1682d ago

PHP version history (2 changes)v1.0.0PHP ^7.1.3

v1.1.1PHP ^7.1.3 || ^8.0 || ^9.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/55d89f2d44fb12225de2119994028ee69e36770bcf33c2b1ddf0d6672d28151b?d=identicon)[filippo.toso](/maintainers/filippo.toso)

---

Top Contributors

[![filippotoso](https://avatars.githubusercontent.com/u/26958813?v=4)](https://github.com/filippotoso "filippotoso (7 commits)")

### Embed Badge

![Health badge](/badges/filippo-toso-validate-function/health.svg)

```
[![Health](https://phpackages.com/badges/filippo-toso-validate-function/health.svg)](https://phpackages.com/packages/filippo-toso-validate-function)
```

###  Alternatives

[spatie/laravel-honeypot

Preventing spam submitted through forms

1.6k6.0M60](/packages/spatie-laravel-honeypot)[proengsoft/laravel-jsvalidation

Validate forms transparently with Javascript reusing your Laravel Validation Rules, Messages, and FormRequest

1.1k2.3M49](/packages/proengsoft-laravel-jsvalidation)[wendelladriel/laravel-validated-dto

Data Transfer Objects with validation for Laravel applications

759569.4k13](/packages/wendelladriel-laravel-validated-dto)[galahad/laravel-addressing

Laravel package providing addressing functionality

70316.6k](/packages/galahad-laravel-addressing)[pressbooks/pressbooks

Pressbooks is an open source book publishing tool built on a WordPress multisite platform. Pressbooks outputs books in multiple formats, including PDF, EPUB, web, and a variety of XML flavours, using a theming/templating system, driven by CSS.

44643.1k1](/packages/pressbooks-pressbooks)[illuminatech/validation-composite

Allows uniting several validation rules into a single one for easy re-usage

184485.5k](/packages/illuminatech-validation-composite)

PHPackages © 2026

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