PHP Standalone Validation Library

Overview

Rakit Validation - PHP Standalone Validation Library

Build Status Coverage Status License

PHP Standalone library for validating data. Inspired by Illuminate\Validation Laravel.

Features

  • API like Laravel validation.
  • Array validation.
  • $_FILES validation with multiple file support.
  • Custom attribute aliases.
  • Custom validation messages.
  • Custom rule.

Requirements

  • PHP 7.0 or higher
  • Composer for installation

Quick Start

Installation

composer require "rakit/validation"

Usage

There are two ways to validating data with this library. Using make to make validation object, then validate it using validate. Or just use validate. Examples:

Using make:

<?php

require('vendor/autoload.php');

use Rakit\Validation\Validator;

$validator = new Validator;

// make it
$validation = $validator->make($_POST + $_FILES, [
    'name'                  => 'required',
    'email'                 => 'required|email',
    'password'              => 'required|min:6',
    'confirm_password'      => 'required|same:password',
    'avatar'                => 'required|uploaded_file:0,500K,png,jpeg',
    'skills'                => 'array',
    'skills.*.id'           => 'required|numeric',
    'skills.*.percentage'   => 'required|numeric'
]);

// then validate
$validation->validate();

if ($validation->fails()) {
    // handling errors
    $errors = $validation->errors();
    echo "<pre>";
    print_r($errors->firstOfAll());
    echo "</pre>";
    exit;
} else {
    // validation passes
    echo "Success!";
}

or just validate it:

<?php

require('vendor/autoload.php');

use Rakit\Validation\Validator;

$validator = new Validator;

$validation = $validator->validate($_POST + $_FILES, [
    'name'                  => 'required',
    'email'                 => 'required|email',
    'password'              => 'required|min:6',
    'confirm_password'      => 'required|same:password',
    'avatar'                => 'required|uploaded_file:0,500K,png,jpeg',
    'skills'                => 'array',
    'skills.*.id'           => 'required|numeric',
    'skills.*.percentage'   => 'required|numeric'
]);

if ($validation->fails()) {
	// handling errors
	$errors = $validation->errors();
	echo "<pre>";
	print_r($errors->firstOfAll());
	echo "</pre>";
	exit;
} else {
	// validation passes
	echo "Success!";
}

In this case, 2 examples above will output the same results.

But with make you can setup something like custom invalid message, custom attribute alias, etc before validation running.

Attribute Alias

By default we will transform your attribute into more readable text. For example confirm_password will be displayed as Confirm password. But you can set it anything you want with setAlias or setAliases method.

Example:

$validator = new Validator;

// To set attribute alias, you should use `make` instead `validate`.
$validation->make([
	'province_id' => $_POST['province_id'],
	'district_id' => $_POST['district_id']
], [
	'province_id' => 'required|numeric',
	'district_id' => 'required|numeric'
]);

// now you can set aliases using this way:
$validation->setAlias('province_id', 'Province');
$validation->setAlias('district_id', 'District');

// or this way:
$validation->setAliases([
	'province_id' => 'Province',
	'district_id' => 'District'
]);

// then validate it
$validation->validate();

Now if province_id value is empty, error message would be 'Province is required'.

Custom Validation Message

Before register/set custom messages, here are some variables you can use in your custom messages:

  • :attribute: will replaced into attribute alias.
  • :value: will replaced into stringify value of attribute. For array and object will replaced to json.

And also there are several message variables depends on their rules.

Here are some ways to register/set your custom message(s):

Custom Messages for Validator

With this way, anytime you make validation using make or validate it will set your custom messages for it. It is useful for localization.

To do this, you can set custom messages as first argument constructor like this:

$validator = new Validator([
	'required' => ':attribute harus diisi',
	'email' => ':email tidak valid',
	// etc
]);

// then validation belows will use those custom messages
$validation_a = $validator->validate($dataset_a, $rules_for_a);
$validation_b = $validator->validate($dataset_b, $rules_for_b);

Or using setMessages method like this:

$validator = new Validator;
$validator->setMessages([
	'required' => ':attribute harus diisi',
	'email' => ':email tidak valid',
	// etc
]);

// now validation belows will use those custom messages
$validation_a = $validator->validate($dataset_a, $rules_for_dataset_a);
$validation_b = $validator->validate($dataset_b, $rules_for_dataset_b);

Custom Messages for Validation

Sometimes you may want to set custom messages for specific validation. To do this you can set your custom messages as 3rd argument of $validator->make or $validator->validate like this:

$validator = new Validator;

$validation_a = $validator->validate($dataset_a, $rules_for_dataset_a, [
	'required' => ':attribute harus diisi',
	'email' => ':email tidak valid',
	// etc
]);

Or you can use $validation->setMessages like this:

$validator = new Validator;

$validation_a = $validator->make($dataset_a, $rules_for_dataset_a);
$validation_a->setMessages([
	'required' => ':attribute harus diisi',
	'email' => ':email tidak valid',
	// etc
]);

...

$validation_a->validate();

Custom Message for Specific Attribute Rule

Sometimes you may want to set custom message for specific rule attribute. To do this you can use : as message separator or using chaining methods.

Examples:

$validator = new Validator;

$validation_a = $validator->make($dataset_a, [
	'age' => 'required|min:18'
]);

$validation_a->setMessages([
	'age:min' => '18+ only',
]);

$validation_a->validate();

Or using chaining methods:

$validator = new Validator;

$validation_a = $validator->make($dataset_a, [
	'photo' => [
		'required',
		$validator('uploaded_file')->fileTypes('jpeg|png')->message('Photo must be jpeg/png image')
	]
]);

$validation_a->validate();

Translation

Translation is different with custom messages. Translation may needed when you use custom message for rule in, not_in, mimes, and uploaded_file.

For example if you use rule in:1,2,3 we will set invalid message like "The Attribute only allows '1', '2', or '3'" where part "'1', '2', or '3'" is comes from ":allowed_values" tag. So if you have custom Indonesian message ":attribute hanya memperbolehkan :allowed_values", we will set invalid message like "Attribute hanya memperbolehkan '1', '2', or '3'" which is the "or" word is not part of Indonesian language.

So, to solve this problem, we can use translation like this:

// Set translation for words 'and' and 'or'.
$validator->setTranslations([
    'and' => 'dan',
    'or' => 'atau'
]);

// Set custom message for 'in' rule
$validator->setMessage('in', ":attribute hanya memperbolehkan :allowed_values");

// Validate
$validation = $validator->validate($inputs, [
    'nomor' => 'in:1,2,3'
]);

$message = $validation->errors()->first('nomor'); // "Nomor hanya memperbolehkan '1', '2', atau '3'"

Actually, our built-in rules only use words 'and' and 'or' that you may need to translates.

Working with Error Message

Errors messages are collected in Rakit\Validation\ErrorBag object that you can get it using errors() method.

$validation = $validator->validate($inputs, $rules);

$errors = $validation->errors(); // << ErrorBag

Now you can use methods below to retrieves errors messages:

all(string $format = ':message')

Get all messages as flatten array.

Examples:

$messages = $errors->all();
// [
//     'Email is not valid email',
//     'Password minimum 6 character',
//     'Password must contains capital letters'
// ]

$messages = $errors->all('<li>:message</li>');
// [
//     '<li>Email is not valid email</li>',
//     '<li>Password minimum 6 character</li>',
//     '<li>Password must contains capital letters</li>'
// ]

firstOfAll(string $format = ':message', bool $dotNotation = false)

Get only first message from all existing keys.

Examples:

$messages = $errors->firstOfAll();
// [
//     'email' => Email is not valid email',
//     'password' => 'Password minimum 6 character',
// ]

$messages = $errors->firstOfAll('<li>:message</li>');
// [
//     'email' => '<li>Email is not valid email</li>',
//     'password' => '<li>Password minimum 6 character</li>',
// ]

Argument $dotNotation is for array validation. If it is false it will return original array structure, if it true it will return flatten array with dot notation keys.

For example:

$messages = $errors->firstOfAll(':message', false);
// [
//     'contacts' => [
//          1 => [
//              'email' => 'Email is not valid email',
//              'phone' => 'Phone is not valid phone number'
//          ],
//     ],
// ]

$messages = $errors->firstOfAll(':message', true);
// [
//     'contacts.1.email' => 'Email is not valid email',
//     'contacts.1.phone' => 'Email is not valid phone number',
// ]

first(string $key)

Get first message from given key. It will return string if key has any error message, or null if key has no errors.

For example:

if ($emailError = $errors->first('email')) {
    echo $emailError;
}

toArray()

Get all messages grouped by it's keys.

For example:

$messages = $errors->toArray();
// [
//     'email' => [
//         'Email is not valid email'
//     ],
//     'password' => [
//         'Password minimum 6 character',
//         'Password must contains capital letters'
//     ]
// ]

count()

Get count messages.

has(string $key)

Check if given key has an error. It returns bool if a key has an error, and otherwise.

Getting Validated, Valid, and Invalid Data

For example you have validation like this:

$validation = $validator->validate([
    'title' => 'Lorem Ipsum',
    'body' => 'Lorem ipsum dolor sit amet ...',
    'published' => null,
    'something' => '-invalid-'
], [
    'title' => 'required',
    'body' => 'required',
    'published' => 'default:1|required|in:0,1',
    'something' => 'required|numeric'
]);

You can get validated data, valid data, or invalid data using methods in example below:

$validatedData = $validation->getValidatedData();
// [
//     'title' => 'Lorem Ipsum',
//     'body' => 'Lorem ipsum dolor sit amet ...',
//     'published' => '1' // notice this
//     'something' => '-invalid-'
// ]

$validData = $validation->getValidData();
// [
//     'title' => 'Lorem Ipsum',
//     'body' => 'Lorem ipsum dolor sit amet ...',
//     'published' => '1'
// ]

$invalidData = $validation->getInvalidData();
// [
//     'something' => '-invalid-'
// ]

Available Rules

Click to show details.

required

The field under this validation must be present and not 'empty'.

Here are some examples:

Value Valid
'something' true
'0' true
0 true
[0] true
[null] true
null false
[] false
'' false

For uploaded file, $_FILES['key']['error'] must not UPLOAD_ERR_NO_FILE.

required_if:another_field,value_1,value_2,...

The field under this rule must be present and not empty if the anotherfield field is equal to any value.

For example required_if:something,1,yes,on will be required if something value is one of 1, '1', 'yes', or 'on'.

required_unless:another_field,value_1,value_2,...

The field under validation must be present and not empty unless the anotherfield field is equal to any value.

required_with:field_1,field_2,...

The field under validation must be present and not empty only if any of the other specified fields are present.

required_without:field_1,field_2,...

The field under validation must be present and not empty only when any of the other specified fields are not present.

required_with_all:field_1,field_2,...

The field under validation must be present and not empty only if all of the other specified fields are present.

required_without_all:field_1,field_2,...

The field under validation must be present and not empty only when all of the other specified fields are not present.

uploaded_file:min_size,max_size,extension_a,extension_b,...

This rule will validate data from $_FILES. Field under this rule must be follows rules below to be valid:

  • $_FILES['key']['error'] must be UPLOAD_ERR_OK or UPLOAD_ERR_NO_FILE. For UPLOAD_ERR_NO_FILE you can validate it with required rule.
  • If min size is given, uploaded file size MUST NOT be lower than min size.
  • If max size is given, uploaded file size MUST NOT be higher than max size.
  • If file types is given, mime type must be one of those given types.

Here are some example definitions and explanations:

  • uploaded_file: uploaded file is optional. When it is not empty, it must be ERR_UPLOAD_OK.
  • required|uploaded_file: uploaded file is required, and it must be ERR_UPLOAD_OK.
  • uploaded_file:0,1M: uploaded file size must be between 0 - 1 MB, but uploaded file is optional.
  • required|uploaded_file:0,1M,png,jpeg: uploaded file size must be between 0 - 1MB and mime types must be image/jpeg or image/png.

Optionally, if you want to have separate error message between size and type validation. You can use mimes rule to validate file types, and min, max, or between to validate it's size.

For multiple file upload, PHP will give you undesirable array $_FILES structure (here is the topic). So we make uploaded_file rule to automatically resolve your $_FILES value to be well-organized array structure. That means, you cannot only use min, max, between, or mimes rules to validate multiple file upload. You should put uploaded_file just to resolve it's value and make sure that value is correct uploaded file value.

For example if you have input files like this:

<input type="file" name="photos[]"/>
<input type="file" name="photos[]"/>
<input type="file" name="photos[]"/>

You can simply validate it like this:

$validation = $validator->validate($_FILES, [
    'photos.*' => 'uploaded_file:0,2M,jpeg,png'
]);

// or

$validation = $validator->validate($_FILES, [
    'photos.*' => 'uploaded_file|max:2M|mimes:jpeg,png'
]);

Or if you have input files like this:

<input type="file" name="images[profile]"/>
<input type="file" name="images[cover]"/>

You can validate it like this:

$validation = $validator->validate($_FILES, [
    'images.*' => 'uploaded_file|max:2M|mimes:jpeg,png',
]);

// or

$validation = $validator->validate($_FILES, [
    'images.profile' => 'uploaded_file|max:2M|mimes:jpeg,png',
    'images.cover' => 'uploaded_file|max:5M|mimes:jpeg,png',
]);

Now when you use getValidData() or getInvalidData() you will get well array structure just like single file upload.

mimes:extension_a,extension_b,...

The $_FILES item under validation must have a MIME type corresponding to one of the listed extensions.

default/defaults

This is special rule that doesn't validate anything. It just set default value to your attribute if that attribute is empty or not present.

For example if you have validation like this

$validation = $validator->validate([
    'enabled' => null
], [
    'enabled' => 'default:1|required|in:0,1'
    'published' => 'default:0|required|in:0,1'
]);

$validation->passes(); // true

// Get the valid/default data
$valid_data = $validation->getValidData();

$enabled = $valid_data['enabled'];
$published = $valid_data['published'];

Validation passes because we sets default value for enabled and published to 1 and 0 which is valid. Then we can get the valid/default data.

email

The field under this validation must be valid email address.

uppercase

The field under this validation must be valid uppercase.

lowercase

The field under this validation must be valid lowercase.

json

The field under this validation must be valid JSON string.

alpha

The field under this rule must be entirely alphabetic characters.

numeric

The field under this rule must be numeric.

alpha_num

The field under this rule must be entirely alpha-numeric characters.

alpha_dash

The field under this rule may have alpha-numeric characters, as well as dashes and underscores.

alpha_spaces

The field under this rule may have alpha characters, as well as spaces.

in:value_1,value_2,...

The field under this rule must be included in the given list of values.

This rule is using in_array to check the value. By default in_array disable strict checking. So it doesn't check data type. If you want enable strict checking, you can invoke validator like this:

$validation = $validator->validate($data, [
    'enabled' => [
        'required',
        $validator('in', [true, 1])->strict()
    ]
]);

Then 'enabled' value should be boolean true, or int 1.

not_in:value_1,value_2,...

The field under this rule must not be included in the given list of values.

This rule also using in_array. You can enable strict checking by invoking validator and call strict() like example in rule in above.

min:number

The field under this rule must have a size greater or equal than the given number.

For string value, size corresponds to the number of characters. For integer or float value, size corresponds to its numerical value. For an array, size corresponds to the count of the array. If your value is numeric string, you can put numeric rule to treat its size by numeric value instead of number of characters.

You can also validate uploaded file using this rule to validate minimum size of uploaded file. For example:

$validation = $validator->validate([
    'photo' => $_FILES['photo']
], [
    'photo' => 'required|min:1M'
]);
max:number

The field under this rule must have a size lower or equal than the given number. Value size calculated in same way like min rule.

You can also validate uploaded file using this rule to validate maximum size of uploaded file. For example:

$validation = $validator->validate([
    'photo' => $_FILES['photo']
], [
    'photo' => 'required|max:2M'
]);
between:min,max

The field under this rule must have a size between min and max params. Value size calculated in same way like min and max rule.

You can also validate uploaded file using this rule to validate size of uploaded file. For example:

$validation = $validator->validate([
    'photo' => $_FILES['photo']
], [
    'photo' => 'required|between:1M,2M'
]);
digits:value

The field under validation must be numeric and must have an exact length of value.

digits_between:min,max

The field under validation must have a length between the given min and max.

url

The field under this rule must be valid url format. By default it check common URL scheme format like any_scheme://.... But you can specify URL schemes if you want.

For example:

$validation = $validator->validate($inputs, [
    'random_url' => 'url',          // value can be `any_scheme://...`
    'https_url' => 'url:http',      // value must be started with `https://`
    'http_url' => 'url:http,https', // value must be started with `http://` or `https://`
    'ftp_url' => 'url:ftp',         // value must be started with `ftp://`
    'custom_url' => 'url:custom',   // value must be started with `custom://`
    'mailto_url' => 'url:mailto',   // value must conatin valid mailto URL scheme like `mailto:[email protected],[email protected]`
    'jdbc_url' => 'url:jdbc',       // value must contain valid jdbc URL scheme like `jdbc:mysql://localhost/dbname`
]);

For common URL scheme and mailto, we combine FILTER_VALIDATE_URL to validate URL format and preg_match to validate it's scheme. Except for JDBC URL, currently it just check a valid JDBC scheme.

integer The field under t rule must be integer.
boolean

The field under this rule must be boolean. Accepted input are true, false, 1, 0, "1", and "0".

ip

The field under this rule must be valid ipv4 or ipv6.

ipv4

The field under this rule must be valid ipv4.

ipv6

The field under this rule must be valid ipv6.

extension:extension_a,extension_b,...

The field under this rule must end with an extension corresponding to one of those listed.

This is useful for validating a file type for a given a path or url. The mimes rule should be used for validating uploads.

array

The field under this rule must be array.

same:another_field

The field value under this rule must be same with another_field value.

regex:/your-regex/

The field under this rule must be match with given regex.

date:format

The field under this rule must be valid date format. Parameter format is optional, default format is Y-m-d.

accepted

The field under this rule must be one of 'on', 'yes', '1', 'true', or true.

present

The field under this rule must be exists, whatever the value is.

different:another_field

Opposite of same. The field value under this rule must be different with another_field value.

after:tomorrow

Anything that can be parsed by strtotime can be passed as a parameter to this rule. Valid examples include :

  • after:next week
  • after:2016-12-31
  • after:2016
  • after:2016-12-31 09:56:02
before:yesterday

This also works the same way as the after rule. Pass anything that can be parsed by strtotime

callback

You can use this rule to define your own validation rule. This rule can't be registered using string pipe. To use this rule, you should put Closure inside array of rules.

For example:

$validation = $validator->validate($_POST, [
    'even_number' => [
        'required',
        function ($value) {
            // false = invalid
            return (is_numeric($value) AND $value % 2 === 0);
        }
    ]
]);

You can set invalid message by returning a string. For example, example above would be:

$validation = $validator->validate($_POST, [
    'even_number' => [
        'required',
        function ($value) {
            if (!is_numeric($value)) {
                return ":attribute must be numeric.";
            }
            if ($value % 2 !== 0) {
                return ":attribute is not even number.";
            }
            // you can return true or don't return anything if value is valid
        }
    ]
]);

Note: Rakit\Validation\Rules\Callback instance is binded into your Closure. So you can access rule properties and methods using $this.

nullable

Field under this rule may be empty.

Register/Override Rule

Another way to use custom validation rule is to create a class extending Rakit\Validation\Rule. Then register it using setValidator or addValidator.

For example, you want to create unique validator that check field availability from database.

First, lets create UniqueRule class:

<?php

use Rakit\Validation\Rule;

class UniqueRule extends Rule
{
    protected $message = ":attribute :value has been used";

    protected $fillableParams = ['table', 'column', 'except'];

    protected $pdo;

    public function __construct(PDO $pdo)
    {
        $this->pdo = $pdo;
    }

    public function check($value): bool
    {
        // make sure required parameters exists
        $this->requireParameters(['table', 'column']);

        // getting parameters
        $column = $this->parameter('column');
        $table = $this->parameter('table');
        $except = $this->parameter('except');

        if ($except AND $except == $value) {
            return true;
        }

        // do query
        $stmt = $this->pdo->prepare("select count(*) as count from `{$table}` where `{$column}` = :value");
        $stmt->bindParam(':value', $value);
        $stmt->execute();
        $data = $stmt->fetch(PDO::FETCH_ASSOC);

        // true for valid, false for invalid
        return intval($data['count']) === 0;
    }
}

Then you need to register UniqueRule instance into validator like this:

use Rakit\Validation\Validator;

$validator = new Validator;

$validator->addValidator('unique', new UniqueRule($pdo));

Now you can use it like this:

$validation = $validator->validate($_POST, [
    'email' => 'email|unique:users,email,[email protected]'
]);

In UniqueRule above, property $message is used for default invalid message. And property $fillable_params is used for fillParameters method (defined in Rakit\Validation\Rule class). By default fillParameters will fill parameters listed in $fillable_params. For example unique:users,email,[email protected] in example above, will set:

$params['table'] = 'users';
$params['column'] = 'email';
$params['except'] = '[email protected]';

If you want your custom rule accept parameter list like in,not_in, or uploaded_file rules, you just need to override fillParameters(array $params) method in your custom rule class.

Note that unique rule that we created above also can be used like this:

$validation = $validator->validate($_POST, [
    'email' => [
    	'required', 'email',
    	$validator('unique', 'users', 'email')->message('Custom message')
    ]
]);

So you can improve UniqueRule class above by adding some methods that returning its own instance like this:

<?php

use Rakit\Validation\Rule;

class UniqueRule extends Rule
{
    ...

    public function table($table)
    {
        $this->params['table'] = $table;
        return $this;
    }

    public function column($column)
    {
        $this->params['column'] = $column;
        return $this;
    }

    public function except($value)
    {
        $this->params['except'] = $value;
        return $this;
    }

    ...
}

Then you can use it in more funky way like this:

$validation = $validator->validate($_POST, [
    'email' => [
    	'required', 'email',
    	$validator('unique')->table('users')->column('email')->except('[email protected]')->message('Custom message')
    ]
]);

Implicit Rule

Implicit rule is a rule that if it's invalid, then next rules will be ignored. For example if attribute didn't pass required* rules, mostly it's next rules will also be invalids. So to prevent our next rules messages to get collected, we make required* rules to be implicit.

To make your custom rule implicit, you can make $implicit property value to be true. For example:

<?php

use Rakit\Validation\Rule;

class YourCustomRule extends Rule
{

    protected $implicit = true;

}

Modify Value

In some case, you may want your custom rule to be able to modify it's attribute value like our default/defaults rule. So in current and next rules checks, your modified value will be used.

To do this, you should implements Rakit\Validation\Rules\Interfaces\ModifyValue and create method modifyValue($value) to your custom rule class.

For example:

<?php

use Rakit\Validation\Rule;
use Rakit\Validation\Rules\Interfaces\ModifyValue;

class YourCustomRule extends Rule implements ModifyValue
{
    ...

    public function modifyValue($value)
    {
        // Do something with $value

        return $value;
    }

    ...
}

Before Validation Hook

You may want to do some preparation before validation running. For example our uploaded_file rule will resolves attribute value that come from $_FILES (undesirable) array structure to be well-organized array structure, so we can validate multiple file upload just like validating other data.

To do this, you should implements Rakit\Validation\Rules\Interfaces\BeforeValidate and create method beforeValidate() to your custom rule class.

For example:

<?php

use Rakit\Validation\Rule;
use Rakit\Validation\Rules\Interfaces\BeforeValidate;

class YourCustomRule extends Rule implements BeforeValidate
{
    ...

    public function beforeValidate()
    {
        $attribute = $this->getAttribute(); // Rakit\Validation\Attribute instance
        $validation = $this->validation; // Rakit\Validation\Validation instance

        // Do something with $attribute and $validation
        // For example change attribute value
        $validation->setValue($attribute->getKey(), "your custom value");
    }

    ...
}
Comments
  • Discussion and Progress for v1 Release

    Discussion and Progress for v1 Release

    Beforehand, I want to say thank you for your contributions and inputs so far :bowing_man:

    I wanna make some major changes to this package based on previous issues and my experience. But actually, I've rarely used PHP lately, especially this package. And because it would be a v1 (stable release), I want to implement best practices to our codes. So I need your inputs and suggestions to do this.

    So far, this is my to-do lists for v1:

    • [x] Drop support for PHP 5. Minimum support is PHP 7.0. #62
    • [x] Change ErrorBag::firstOrAll to return array assoc instead of indexed array. #64
    • [x] ~~Split uploaded_file rule to uploaded_filesize and uploaded_filetype so we get separate error message~~. Add mimes to validate uploaded file mimes, and update min, max, and between rules to be able to validate uploaded file size. #69
    • [x] Adding doc comments to methods and properties. #67
    • [x] Adding type hint and return type. #67
    • [x] Fixing some inconsistency in variable naming and format. #66
    • [x] Improve documentation. #70 #72
    • [x] Support multiple file upload. #71

    And as I'm not fluent in English. Any misspelled correction in the documentation would be appreciated.

    I have created branch v1 for this release. So we can make some PR to that branch. And start from now, only bugfixes are allowed to merged to master. Any other minor changes would be merged to v1. I will merge v1 to master after we have done those to-do lists.

    Thank you.

    opened by emsifa 11
  • Questions about the uploaded file rule

    Questions about the uploaded file rule

    Hi @emsifa ,

    • Why are you checking if a file is valid by just the array keys ? https://github.com/rakit/validation/blob/master/src/Rules/UploadedFile.php#L105-#L114 . You could resort to is_uploaded_file. This seems very much safer than the current implementation available.

    Plus there seem to be a bug here 😀 https://github.com/rakit/validation/blob/master/src/Validator.php#L26-#L28

    opened by adelowo 10
  • required only if value exists/not empty?

    required only if value exists/not empty?

    i'm new at using this library, and i am looking for an option that only validates if the field is not empty, if empty "remove" from valid data, its because i have an update user page, and the blank fields are not to update

    opened by tdias25 7
  • How to make a multiple file input required?

    How to make a multiple file input required?

    I have input: <input type="file" name="document[]">

    I made validation: 'document.*' => 'required|uploaded_file:0,10M,pdf,jpeg,jpg',

    But, its did't work. An empty field is validated. Please, help me.

    opened by IgorNoskov 6
  • Custom Validation Message

    Custom Validation Message

    Hi, there. Thanks for sharing with us this amazing class!

    Well, my validation code is working pretty well but I didn't understand how to custom validation messages. I want to do that cause I need generate messages into brazilian portuguese.

    See the below code:

    $validation = $validator->make($_POST, [
          'name' => 'required|min:3',
          'age' => 'required|numeric'
        ]);
    

    How do I custom messages to those fields using rakit class?

    Thanks in advance.

    opened by rogerioitcom 6
  • URL validation is minimal at best

    URL validation is minimal at best

    FILTER_VALIDATE_URL is a minimal validation filter, as documented in the PHP docs:

    [FILTER_VALIDATE_URL] Validates value as URL (according to » http://www.faqs.org/rfcs/rfc2396), optionally with required components. Beware a valid URL may not specify the HTTP protocol http:// so further validation may be required to determine the URL uses an expected protocol, e.g. ssh:// or mailto:. Note that the function will only find ASCII URLs to be valid; internationalized domain names (containing non-ASCII characters) will fail. @sauce

    At a minimum, I think a secondary validation should be made to detect the presense of a URL protocol:

    <?php
        // update to the /src/Rules/Url.php file
        public function check($value)
        {
            return filter_var($value, FILTER_VALIDATE_URL) !== false &&
                preg_match('/^[\w]{2,6}:\/\//', $value);
        }
    

    I may look into issuing a PR later this evening/week when I can get to it but I've already tested and validated the REGEX provided works just fine.

    opened by bmcminn 5
  • Vertical bar in regex rule

    Vertical bar in regex rule

    Can't use vertical bar in regex rule Example:

    $regex_rule = [ 'name' => 'regex:/(aaa|bbb)/'];
    

    Result: Fatal error: Uncaught Rakit\Validation\RuleNotFoundException: Validator 'bbb)/' is not registered

    opened by Elmsellem 4
  • between validation not working

    between validation not working

    I sending value 33 as actionID which has the follow validate rules: required|numeric|between:1,11 edit: also tried min/max also not working

    	$validator = new Validator;
    	$validation = $validator->make($this->request->data, [
    		'planID' => 'required',
    		'actionID' => 'required|numeric|between:1,11',
    		'value' => 'required|numeric|between:0,1',
    	]);
    	$validation->validate();
    	if ($validation->fails()) {
    		Logger::log("updatePrompts", 'data invalid -> ' . json_encode($this->request->data), __FILE__, __LINE__);
    		return $this->view->renderFail();
    	}
    

    it's still passes the validate.. even if the number is out of boundry..

    opened by LeonBeilis 4
  • Regex with | symbol

    Regex with | symbol

    I tried this expression: required|regex:/^\d$|^(?:\d+\,?)+\d+$/, and catch the error with message "Uncaught exception: 'Rakit\Validation\RuleNotFoundException" with message 'Validator '^(?' is not registered". The symbol | don't work in an expression.

    opened by IgorNoskov 4
  • Regex rule breaks when the regex contains pipe character(s)

    Regex rule breaks when the regex contains pipe character(s)

    A regex rule containing the pipe (|) character such as...

    url|regex:/^.*\.(jpg|JPG|gif|GIF|doc|DOC|pdf|PDF)$/

    ... breaks the Regex validator:

    Fatal error: Uncaught Rakit\Validation\RuleNotFoundException: Validator 'JPG' is not registered in ..vendor/rakit/validation/src/Validator.php on line 103
    

    I'm trying to validate the extension based on an existing file's url. It would be nice if there was a built in validator similar to mime to achieve this for when we're handling file urls/paths in the input rather than as a $_FILES upload. Although the regex would suffice if this can be fixed!

    Awesome library by the way :)

    opened by thomasfw 4
  • Test enhancement

    Test enhancement

    Changed log

    • Set different PHPUnit versions to support multiple PHP versions.
    • Using class-based PHPUnit namespace to be compatible with latest PHPUnit version.
    • Drop the php-5.5 and php-5.6 versions support because these PHP versions will be end of life.
    • Add the namespace for the classes in tests folder.
    • Add the tests/bootstrap.php file to load the all required files once before doing unit test work.
    opened by peter279k 4
  • Before & After: Should not throw an exception if the value is empty.

    Before & After: Should not throw an exception if the value is empty.

    Hey, I have a validator rule like this:

    $validator->make($_POST, 'dateOfBirth'=>'date:Y/m/d|before:today' );

    As you can see, the date field is not required, it is optional, but if someone wants to enter it, it must be in the given format and before today. The problem is when the user leaves the field empty, we get an error that says: ... Argument #1 ($date) must be of type string, null given, called in ...

    So you get the point. I am pretty sure we should leave checking the value for empty/null values for the "required" rule and return true if the field is empty, in "before and after" rules.

    opened by mahyarkhanbabai 0
  • extension parameter not working

    extension parameter not working

    src\Rules\Extension.php

    line 49 $ext = strtolower(pathinfo($value, PATHINFO_EXTENSION)); should be $ext = strtolower(pathinfo($value['name'], PATHINFO_EXTENSION));

    opened by jaydeep-rayl 0
Releases(v1.0.0)
  • v1.0.0(Nov 29, 2018)

    Changelogs

    Added

    • Rule mimes to validate mime types from $_FILE data. (https://github.com/rakit/validation/pull/69/commits/3924708356f106e4b78b17b7999d560f6e4904fd)
    • Method Helper::join to join array of string with given separator and last separator. (https://github.com/rakit/validation/pull/73/commits/8e99f34deb2b70a183b4c2372307dfc700dbc292)
    • Method Helper::wraps to wraps array of string with given prefix and suffix. (https://github.com/rakit/validation/pull/73/commits/8e99f34deb2b70a183b4c2372307dfc700dbc292)
    • Trait Rakit\Validation\Traits\TranslationsTrait contains setter and getter translations. (https://github.com/rakit/validation/pull/73/commits/bb8c375f6b1fba88cf21c6a34cf983ce0d4da645)
    • Method Rule::setParameterText to set custom parameter text that can be used in invalid message. (https://github.com/rakit/validation/pull/73/commits/550c6c4bbc242b10bd39116a6580c86931d12862)
    • Method Rule::getParametersTexts to get custom parameters texts. (https://github.com/rakit/validation/pull/73/commits/550c6c4bbc242b10bd39116a6580c86931d12862)
    • PHP_Codesniffer. (https://github.com/rakit/validation/pull/66/commits/91ff9278da1f492f9e32f4f6ad41fe3dcf29e209)
    • Typehints and PHPDoc comments. (#67)

    Changed

    • PHP minimum version from 5.5 to 7.0. (#62)
    • Rule uploaded_file can be used to validate multiple file uploads. (#71)
    • Rakit\Validation\ErrorBag::firstOfAll() return array assoc instead of indexed array. (https://github.com/rakit/validation/pull/64/commits/69b5110620d1538543f95621f882e6a8c600931a)
    • Rakit\Validation\Rule::check() must return bool. (#68)
    • Rules min, max, and between can be used to validate uploaded file size from $_FILES. (https://github.com/rakit/validation/pull/69/commits/ae3a47b2b1c3570f312dc63abbcebfa0a28cdfa3)
    • Rule uploaded_file default message is dynamic depends on what caused. (https://github.com/rakit/validation/pull/73/commits/0db92799456d2ffcd8b387fe1b57a41dfee5b1e8)
    • Rule in and not_in default messages shows what options are allowed or not allowed. (https://github.com/rakit/validation/pull/73/commits/0db92799456d2ffcd8b387fe1b57a41dfee5b1e8)
    • Rule default using trait Rakit\Validation\Rules\Traits\ModifyValue to modify value if it's empty. (#71)
    Source code(tar.gz)
    Source code(zip)
Owner
Rakit Lab
PHP library dan framework rakitan
Rakit Lab
A standalone Amazon S3 (REST) client for PHP 5/CURL

Amazon S3 PHP Class Usage OO method (e,g; $s3->getObject(...)): $s3 = new S3($awsAccessKey, $awsSecretKey); Statically (e,g; S3::getObject(...)): S3::

Donovan Schönknecht 1k Aug 24, 2022
Pat eu cookies law - 🌝 EU Cookie Law Compliance: A Textpattern plugin (or standalone script) for Third-Party Cookies (RGPD compliance)

pat_eu_cookies_law EU Cookie Law Compliance: A Textpattern plugin (or a standalone script) for Third-Party Cookies. A simple solution that respects th

Patrick LEFEVRE 3 Aug 16, 2020
The Pantheon CLI — a standalone utility for performing operations on the Pantheon Platform

terminus : Pantheon's Command-Line Interface Status About Terminus is Pantheon's Command Line Interface (CLI), providing at least equivalent functiona

Pantheon 287 Jul 15, 2022
The last validation library you will ever need!

Mighty The last validation library you will ever need! Table of Contents Installation About Mighty Quickstart Mighty Validation Expression Language Ex

Marwan Al-Soltany 49 Sep 29, 2022
PHP Japanese string helper functions for converting Japanese strings from full-width to half-width and reverse. Laravel Rule for validation Japanese string only full-width or only half-width.

Japanese String Helpers PHP Japanese string helper functions for converting Japanese strings from full-width to half-width and reverse. Laravel Rule f

Deha 54 Mar 22, 2022
File uploads with validation and storage strategies

Upload This component simplifies file validation and uploading. Usage Assume a file is uploaded with this HTML form: <form method="POST" enctype="mult

Brandon Savage 1.7k Sep 19, 2022
The main scope of this extension is to help phpstan to detect the type of object after the Assert\Assertion validation.

PHPStan beberlei/assert extension PHPStan beberlei/assert Description The main scope of this extension is to help phpstan to detect the type of object

PHPStan 33 Aug 2, 2022
This component simplifies file validation and uploading.

This component simplifies file validation and uploading.

Brandon Savage 1.7k Sep 19, 2022
File Upload widget with multiple file selection, drag&drop support, progress bar, validation and preview images, audio and video for jQuery

File Upload widget with multiple file selection, drag&drop support, progress bar, validation and preview images, audio and video for jQuery. Supports cross-domain, chunked and resumable file uploads. Works with any server-side platform (Google App Engine, PHP, Python, Ruby on Rails, Java, etc.) that supports standard HTML form file uploads.

Sebastian Tschan 31.1k Sep 23, 2022
Easy to use utility functions for everyday PHP projects. This is a port of the Lodash JS library to PHP

Lodash-PHP Lodash-PHP is a port of the Lodash JS library to PHP. It is a set of easy to use utility functions for everyday PHP projects. Lodash-PHP tr

Lodash PHP 466 Sep 15, 2022
PHP Text Analysis is a library for performing Information Retrieval (IR) and Natural Language Processing (NLP) tasks using the PHP language

php-text-analysis PHP Text Analysis is a library for performing Information Retrieval (IR) and Natural Language Processing (NLP) tasks using the PHP l

null 458 Sep 12, 2022
php-echarts is a php library for the echarts 5.0.

php-echarts 一款支持Apache EChart5.0+图表的php开发库 优先ThinkPHP5/6的开发及测试。 Apache EChart5.0已经最新发布,在视觉效果、动画效果和大数据展示方面已经远超之前的版本; 故不考虑EChart5.0之前版本的兼容问题;建议直接尝试5.0+

youyiio 5 Aug 15, 2022
Minimalist PHP frame for Core-Library, for Developing PHP application that gives you the full control of your application.

LazyPHP lightweight Pre-Made Frame for Core-library Install Run the below command in your terminal $ composer create-project ryzen/lazyphp my-first-pr

Ry-Zen 7 Aug 21, 2022
Gettext is a PHP (^7.2) library to import/export/edit gettext from PO, MO, PHP, JS files, etc.

Gettext Note: this is the documentation of the new 5.x version. Go to 4.x branch if you're looking for the old 4.x version Created by Oscar Otero http

Gettext 641 Sep 17, 2022
:date: The VObject library for PHP allows you to easily parse and manipulate iCalendar and vCard objects

sabre/vobject The VObject library allows you to easily parse and manipulate iCalendar and vCard objects using PHP. The goal of the VObject library is

sabre.io 525 Sep 23, 2022
Small convention based CQRS library for PHP

LiteCQRS for PHP Small naming-convention based CQRS library for PHP (loosely based on LiteCQRS for C#) that relies on the MessageBus, Command, EventSo

Benjamin Eberlei 563 Sep 12, 2022
Experimental library for forking PHP

Spork: PHP on a Fork <?php $manager = new Spork\ProcessManager(); $manager->fork(function() { // do something in another process! return 'Hel

Kris Wallsmith 588 Jun 25, 2022
Collection pipeline library for PHP

Knapsack Collection pipeline library for PHP Knapsack is a collection library for PHP >= 5.6 that implements most of the sequence operations proposed

Dušan Kasan 538 Aug 27, 2022
A PHP library to play with the Raspberry PI's GPIO pins

php-gpio php-gpio is a simple PHP library to play with the Raspberry PI's GPIO pins. It provides simple tools such as reading & writing to pins. [UPDA

Ronan Guilloux 265 Sep 3, 2022