Skip to content

Commit

Permalink
Merge pull request #1187 from nowackipawel/patch-2
Browse files Browse the repository at this point in the history
Adds valid_json which is using json_last_error() === JSON_ERROR_NONE
lonnieezell authored Sep 4, 2018

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
2 parents ebdd40d + 7378a21 commit ded0479
Showing 3 changed files with 54 additions and 0 deletions.
15 changes: 15 additions & 0 deletions system/Validation/FormatRules.php
Original file line number Diff line number Diff line change
@@ -241,6 +241,21 @@ public function valid_base64(string $str = null): bool

//--------------------------------------------------------------------

/**
* Valid JSON
*
* @param string
*
* @return bool
*/
public function valid_json(string $str = null): bool
{
json_decode($str);
return json_last_error() === JSON_ERROR_NONE;
}

//--------------------------------------------------------------------

/**
* Checks for a correctly formatted email address
*
38 changes: 38 additions & 0 deletions tests/system/Validation/FormatRulesTest.php
Original file line number Diff line number Diff line change
@@ -596,6 +596,44 @@ public function base64Provider()

//-------------------------------------------------------------------

/**
* @dataProvider jsonProvider
*
* @param $str
* @param $expected
*/
public function testJson($first, $expected)
{
$data = [
'foo' => $first,
];

$this->validation->setRules([
'foo' => "valid_json",
]);

$this->assertEquals($expected, $this->validation->run($data));
}

//--------------------------------------------------------------------

public function jsonProvider()
{
return [
['null', true],
['"null"', true],
['600100825', true],
['{"A":"Yay.", "B":[0,5]}', true],
['[0,"2",2.2,"3.3"]', true],
[null, false],
['600-Nope. Should not pass.', false],
['{"A":SHOULD_NOT_PASS}', false],
['[0,"2",2.2 "3.3"]', false]
];
}

//-------------------------------------------------------------------

/**
* @dataProvider timezoneProvider
*
1 change: 1 addition & 0 deletions user_guide_src/source/libraries/validation.rst
Original file line number Diff line number Diff line change
@@ -670,6 +670,7 @@ is_unique Yes Checks if this field value exists in the dat
column and value to ignore, useful when updating records to ignore itself.
timezone No Fails if field does match a timezone per ``timezone_identifiers_list``
valid_base64 No Fails if field contains anything other than valid Base64 characters.
valid_json No Fails if field does not contain a valid JSON string.
valid_email No Fails if field does not contain a valid email address.
valid_emails No Fails if any value provided in a comma separated list is not a valid email.
valid_ip No Fails if the supplied IP is not valid. Accepts an optional parameter of ‘ipv4’ or valid_ip[ipv6]

0 comments on commit ded0479

Please sign in to comment.