dev-master
9999999-devA json validator
MIT
The Requires
- php >=7.0.0
The Development Requires
by Jin Hu
json
v0.1.0
0.1.0.0A json validator
MIT
The Requires
- php >=7.0.0
The Development Requires
by Jin Hu
json
A json validator
A JSON Validator that designed to be elegant and easy to use., (*1)
JSON Validation is a common task in automated API testing, JSON-Schema is complex and not easy to use, so i created this library to simplify the JSON validation process and made JSON validation more elegant and fun., (*2)
You can install the latest version of JSON validator with the following command:, (*3)
composer require rethink/json-validator:dev-master
By default, JSON Validator shipped with seven kinds of built-in types:, (*4)
Besides the built-in types, it is possible to define your custom type via defineType()
method., (*5)
The following code snippets shows how we can define custom types through array or callable., (*6)
$validator->defineType('User', [ 'name' => 'string', 'gender' => 'string', 'age' => '?integer', 'rating' => '?integer|boolean', ]);
This example defines a custom type named User
, which have four properties. name and gender require be a
string, age requires be an integer but allows to be nullable, and rating required to integer or boolean and allows to be null., (*7)
$validator->defineType('UserCollection', ['User']);
This defines UserCollection
to be an array of User
. In order to define a list type, the definition of the type much
contains only one element., (*8)
$validator->defineType('timestamp', function ($value) { if ((!is_string($value) && !is_numeric($value)) || strtotime($value) === false) { return false; } $date = date_parse($value); return checkdate($date['month'], $date['day'], $date['year']); });
It is also possible to define a type using a callable, which is useful to perform some validation on the data. Such as the example above defined a timestamp type, that requires the data to be a valid datetime., (*9)
We can validate a type by the following two steps:, (*10)
use rethink\jsv\Validator; $validator = new Validator(); // $validator->defineType(...) Add your custom type if necessary
$matched = $validator->matches($data, 'User'); if ($matched) { // Validation passed } else { $errors = $validator->getErrors(); }
This example will check whether the given $data
matches the type User
, if validation fails, we can get the error
messages through getErrors()
method., (*11)
In some situations, we may want an object matches our type strictly, we can utilizing strict mode
to achieve this,
the following is the example:, (*12)
$data = [ 'name' => 'Bob', 'gender' => 'Male', 'age' => 19, 'phone' => null, // This property is unnecessary ]; $matched = $validator->matches($data, 'User', true); // strict mode is turned on var_dump($matched); // false is returned