PHPackages                             iqomp/validator - 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. iqomp/validator

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

iqomp/validator
===============

Simple and easy form/object validator

2.3.3(4y ago)0991MITPHP

Since Dec 2Pushed 4y ago1 watchersCompare

[ Source](https://github.com/iqomp/validator)[ Packagist](https://packagist.org/packages/iqomp/validator)[ RSS](/packages/iqomp-validator/feed)WikiDiscussions master Synced 1w ago

READMEChangelogDependencies (1)Versions (14)Used By (1)

iqomp/validator
===============

[](#iqompvalidator)

Simple and easy form/object validator. This module bring two usable class to work with validation, which is `Iqomp\Validator\Validator` that can be used to validate plain object againts list of rules in array. The second class is `Iqomp\Validator\Form` that take nothing ( optionally user generated object to validate ), and take the validation rule from private config. Not only validate, the validator class can also apply filter to the object property to change modify it.

Installation
------------

[](#installation)

```
composer require iqomp/validator
```

Publishing Config
-----------------

[](#publishing-config)

```
php bin/hyperf.php vendor:publish iqomp/validator
```

Validator
---------

[](#validator)

Class `Iqomp\Validator\Validator` can be use to validate object with developer decide list of validation rules.

```
use Iqomp\Validator\Validator;

$rules = [
    'name' => [
        'rules' => [
            'required' => true
        ],
        'filters' => [
            'string' => true
        ]
    ]
];
$object= (object)['name' => 'User'];
list($result, $errors) = Validator::validate($rules, $object);
```

Result `$result` is an object with properties taken from `$object` only if the property has rule defined on `$rules`.

```
stdClass Object
(
    [name] => User
)

```

Result `$errors` is `property-(object)error` pair of array list of errors upon validation. It can be an empty array on no error found.

```
Array
(
    [name] => stdClass Object
        (
            [field] => name
            [code] => 11.0
            [text] => This field is required
            [options] => Array
                (
                    [rules] => Array
                        (
                            [required] => 1
                        )

                    [filters] => Array
                        (
                            [string] => 1
                        )

                )

        )

)

```

### Method

[](#method)

#### static getErrorFormatter(): string

[](#static-geterrorformatter-string)

Get current custom error formatter

#### static setErrorFormatter(string $formatter): void

[](#static-seterrorformatterstring-formatter-void)

Set custom error formatter.

#### static function validate(array $rules, object $object): array

[](#static-function-validatearray-rules-object-object-array)

Validate the object againts list of rules. This action will return array with two member, the first one is validated object, and the second one is list of exists error or empty array if no error exists.

### Validator Rules

[](#validator-rules)

This is all validator rules define by this module.

#### array =&gt; true | assoc | indexed

[](#array--true--assoc--indexed)

Make sure the value is an array, optionally the validator can validate if it's an assoc or indexed array:

```
    // ...
    'rules' => [
        'array' => true // 'assoc', 'indexed'
    ]
    // ...
```

#### boolean|bool =&gt; true

[](#booleanbool--true)

Make sure the value is boolean, it can be `false` or `true`. Other than that is failing the validator

```
    // ...
    'rules' => [
        'boolean' => true
    ]
    // ....
```

#### callback =&gt; Class::method

[](#callback--classmethod)

Validate the value with external class. The value of the rule should be class and method of class handler:

```
    // ...
    'rules' => [
        'callback' => 'Namespace\\Class::method'
    ]
    // ...
```

The callback should return indexed array as `[:code, :params, :text]`. Where `:code`is error code, `:params` is list of parameters to send to translation based on error code, and `:text` is final error message to use if exists. The `:code` will be translated only if `:text` is not defined.

#### date =&gt; {format,min-field,min,max-field,max}

[](#date--formatmin-fieldminmax-fieldmax)

Make sure the value is a known date based on provided format. It can validate with `min`, `max` date. The `min` and `max` can also be taken from other object field.

```
    // ...
    'rules' => [
        'date' => [
            'format' => 'Y-m-d',
            'min' => 'now',
            // 'min-field' => 'date-start',
            'max' => '+12 days',
            // 'max-field' => 'date-end'
        ]
    ]
    // ...
```

#### email =&gt; true

[](#email--true)

Make sure the value is valid email.

```
    // ...
    'rules' => [
        'email' => true
    ]
    // ...
```

#### empty =&gt; false

[](#empty--false)

Make sure the value is not empty ( falsy ). This rule will set `null` as valid. Use it with `required` rule to make sure it's posted and is not falsy.

```
    // ...
    'rules' => [
        'empty' => false
    ]
    // ...
```

#### equals\_to =&gt; field

[](#equals_to--field)

Make sure the value is equals to other object property value. It can be used for `new-password` field on change password action.

```
    // ...
    'rules' => [
        'equals_to' => 'new-password'
    ]
    // ...
```

#### file =&gt; true

[](#file--true)

Make sure the field is `_FILES` property.

```
    // ...
    'rules' => [
        'file' => true
    ]
    // ...
```

#### in =&gt; \[\]

[](#in--)

Make sure the value is one of defined list.

```
    // ...
    'rules' => [
        'in' => ['one','two','three']
    ]
    // ...
```

#### ip =&gt; true | 4 | 6

[](#ip--true--4--6)

Make sure the value is a valid ip address. Optionally, it can validate for IPv4 or IPv6

```
    // ...
    'rules' => [
        'ip' => true // '4' | '6'
    ]
    // ...
```

#### json =&gt; true

[](#json--true)

Make sure the value is valid JSON string. It expect a `string`.

```
    // ...
    'rules' => [
        'json' => true
    ]
    // ...
```

#### length =&gt; {min,max}

[](#length--minmax)

Make sure the value length is in accepted range. The value expecting a string or an array. One of the rule properti `max` or `min` should defined.

```
    // ...
    'rules' => [
        'length' => [
            'min' => 1,
            'max' => 12
        ]
    ]
    // ...
```

#### notin =&gt; \[\]

[](#notin--)

Make sure the value is not one of defined list.

```
    // ...
    'rules' => [
        'notin' => ['one','two','three']
    ]
    // ...
```

#### numeric =&gt; true | {min,max}

[](#numeric--true--minmax)

Make sure the value is numeric. Optionally pass option `min` and or `max`:

```
    // ...
    'rules' => [
        // 'numeric' => true,
        'numeric' => [
            'min' => 1,
            'max' => 12
        ]
    ]
    // ...
```

#### object =&gt; true

[](#object--true)

Make sure the value is an object.

```
    // ...
    'rules' => [
        'object' => true
    ]
    // ...
```

#### regex =&gt; '!x!'

[](#regex--x)

Test string value againts regex.

```
    // ...
    'rules' => [
        'regex' => '![0-9]+!'
    ]
    // ...
```

#### required =&gt; true

[](#required--true)

Make sure the value is present and is not null.

```
    // ...
    'rules' => [
        'required' => true
    ]
    // ...
```

#### req\_on =&gt; {field=&gt;{operator,expected}}

[](#req_on--fieldoperatorexpected)

Make sure the property is exists and is not null only if condition match. This rule require parameter `operator` and `expected` to be exists for every other field.

The value of `operator` is one of `=`, `!=`, `>`, ` [
        'req_on' => [
            'other_field' => [
                'operator' => '=',
                'expected' => 12
            ],
            'more_field' => [
                'operator' => 'in',
                'expected' => ['one','two','three']
            ]
        ]
    ]
    // ...
```

Above rules make sure the value of `object->other_field` is equal to 12 **AND**the value of `object->more_field` is one of `one`, `two`, or `three`. Current field is required only if both of the condition is match.

#### text =&gt; true | slug | alnumdash | alpha | alnum

[](#text--true--slug--alnumdash--alpha--alnum)

Make sure the value is a text. Optionally follow accepted characters.

1. `true` Validate only the type of the value as string
2. `slug` Accept only characters `^[a-z0-9-_]+$`
3. `alnumdash` Accept only characters `^[a-zA-Z0-9-]+$`
4. `alpha` Accept only characters `^[a-zA-Z]+$`
5. `alnum` Accept only characters `^[a-zA-Z0-9]+$`
6. `!regex!` Accept only if the value is match with provided regex

```
    // ...
    'rules' => [
        'text' => true,
        // 'text' => 'slug',
        // 'text' => '!^TR-[0-9]+$!'
    ]
    // ...
```

#### url =&gt; true | { path, query =&gt; true | \[\] }

[](#url--true---path-query--true---)

Make sure the value is valid URL, optionally with path and some query string.

```
    // ...
    'rules' => [
        'url' => true,
        'url' => [
            'path' => true,
            'query' => true,
            'query' => ['page','rpp','q']
        ]
    ]
    // ...
```

### Validator Filters

[](#validator-filters)

#### array =&gt; true

[](#array--true)

Convert the value to array.

```
    // ...
    'filters' => [
        'array' => true
    ]
    // ...
```

#### boolean =&gt; true

[](#boolean--true)

Convert the value to boolean

```
    // ...
    'filters' => [
        'boolean' => true
    ]
    // ...
```

#### float =&gt; true

[](#float--true)

Convert the value to float

```
    // ...
    'filters' => [
        'float' => true
    ]
    // ...
```

#### integer

[](#integer)

Convert the value to integer

```
    // ...
    'filters' => [
        'integer' => true
    ]
    // ...
```

#### json\_encode

[](#json_encode)

Encode the object with `json_encode` function

```
    // ...
    'filters' => [
        'json_encode' => true
    ]
    // ...
```

#### lowercase

[](#lowercase)

Convert the value to lowercase

```
    // ...
    'filters' => [
        'lowercase' => true
    ]
    // ...
```

#### object

[](#object)

Convert the value to object

```
    // ...
    'filters' => [
        'object' => true
    ]
    // ...
```

#### round =&gt; true | decimal

[](#round--true--decimal)

Round the numeric value. Optionally set total decimal.

```
    // ...
    'filters' => [
        // 'round' => true,
        'round' => 2
    ]
    // ...
```

#### string

[](#string)

Convert the value to string

```
    // ...
    'filters' => [
        'string' => true
    ]
    // ...
```

#### ucwords

[](#ucwords)

Convert the value with function `ucwords`

```
    // ...
    'filters' => [
        'ucwords' => true
    ]
    // ...
```

#### uppercase

[](#uppercase)

Convert the value to uppercase

```
    // ...
    'filters' => [
        'uppercase' => true
    ]
    // ...
```

### Custom Validation Rule

[](#custom-validation-rule)

Please follow below steps to create new validation rule

#### Create Rule Handler

[](#create-rule-handler)

Create new class that handle the validation.

```
