diff --git a/README.md b/README.md index dd4792a..bb77499 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,7 @@ bool endswith(mixed $input, string $match) bool contains(mixed $input, string $match) bool regex(mixed $input, string $regex) bool inlist(mixed $input, array $list) +bool json(mixed $input) ``` ### Validation Engine diff --git a/src/Validator.php b/src/Validator.php index 6233899..44cfb71 100644 --- a/src/Validator.php +++ b/src/Validator.php @@ -242,4 +242,15 @@ public static function inlist($input = null, $list = []) return in_array($input, $list); } + + public static function json($input = null) + { + if (empty($input)) { + return true; + } + + $attempted_parsed_json = json_decode($input, true); + + return ( $attempted_parsed_json !== null ); + } } diff --git a/tests/ValidatorTests.php b/tests/ValidatorTests.php index 075e263..967add4 100644 --- a/tests/ValidatorTests.php +++ b/tests/ValidatorTests.php @@ -300,4 +300,24 @@ public function testShouldPassInlist() $this->assertTrue(Validator::inlist(null, ['ABC','DEF'])); $this->assertTrue(Validator::inlist('ABC', ['ABC','DEF'])); } + + public function testShouldFailJson() + { + $this->assertFalse(Validator::json('asd;flkj')); + } + + public function testShouldPassJson() + { + $this->assertTrue(Validator::json('{"widget": { + "debug": "on", + "window": { + "title": "Sample Konfabulator Widget", + "name": "main_window", + "width": 500, + "height": 500 + }}}' + )); + + $this->assertTrue(Validator::json('{}')); + } }