diff --git a/README.md b/README.md index 35a14bc..c9ac868 100644 --- a/README.md +++ b/README.md @@ -274,6 +274,7 @@ Below is list of all available validation rules * [email](#rule-email) * [uppercase](#rule-uppercase) * [lowercase](#rule-lowercase) +* [json](#rule-json) * [alpha](#rule-alpha) * [numeric](#rule-numeric) * [alpha_num](#rule-alpha_num) @@ -404,6 +405,11 @@ The field under this validation must be valid uppercase. The field under this validation must be valid lowercase. + +#### json + +The field under this validation must be valid JSON string. + #### alpha diff --git a/src/Rules/Json.php b/src/Rules/Json.php new file mode 100644 index 0000000..3a9337b --- /dev/null +++ b/src/Rules/Json.php @@ -0,0 +1,27 @@ + new Rules\After, 'lowercase' => new Rules\Lowercase, 'uppercase' => new Rules\Uppercase, + 'json' => new Rules\Json, 'defaults' => new Rules\Defaults, 'default' => new Rules\Defaults, // alias of defaults ]; diff --git a/tests/Fixtures/Even.php b/tests/Fixtures/Even.php new file mode 100644 index 0000000..cc0ea6d --- /dev/null +++ b/tests/Fixtures/Even.php @@ -0,0 +1,18 @@ +rule = new Json; + } + + public function testValids() + { + $this->assertTrue($this->rule->check('{}')); + $this->assertTrue($this->rule->check('[]')); + $this->assertTrue($this->rule->check('false')); + $this->assertTrue($this->rule->check('null')); + $this->assertTrue($this->rule->check('{"username": "John Doe"}')); + $this->assertTrue($this->rule->check('{"number": 12345678}')); + } + + public function testInvalids() + { + $this->assertFalse($this->rule->check('')); + $this->assertFalse($this->rule->check(123)); + $this->assertFalse($this->rule->check(false)); + $this->assertFalse($this->rule->check('{"username": John Doe}')); + $this->assertFalse($this->rule->check('{number: 12345678}')); + } + +} + diff --git a/tests/ValidatorTest.php b/tests/ValidatorTest.php index dc7827f..9a06036 100644 --- a/tests/ValidatorTest.php +++ b/tests/ValidatorTest.php @@ -2,7 +2,7 @@ use Rakit\Validation\Validator; -require_once 'Fixtures/Json.php'; +require_once 'Fixtures/Even.php'; require_once 'Fixtures/Required.php'; class ValidatorTest extends PHPUnit_Framework_TestCase @@ -339,11 +339,11 @@ public function testAfterRule() public function testNewValidationRuleCanBeAdded() { - $this->validator->addValidator('json', new Json()); + $this->validator->addValidator('even', new Even()); - $data = ['s' => json_encode(['name' => 'space x', 'human' => false])]; + $data = [4, 6, 8, 10 ]; - $validation = $this->validator->make($data, ['s' => 'json'], []); + $validation = $this->validator->make($data, ['s' => 'even'], []); $validation->validate();