Skip to content

Commit

Permalink
feat(Validate): 增加 getFlatMessages 方法,用于获取一维数组的错误信息
Browse files Browse the repository at this point in the history
  • Loading branch information
twinh committed Oct 28, 2020
1 parent b62cd31 commit 023b60b
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
29 changes: 29 additions & 0 deletions lib/Validate.php
Original file line number Diff line number Diff line change
Expand Up @@ -616,6 +616,35 @@ public function getDetailMessages()
return $messages;
}

/**
* Returns invalid messages as a one-dimensional array
*
* Example:
*
* ```
* [
* 'field-required-required' => 'Field is required',
* 'field2-required-required' => 'Field2 is required',
* ]
* ```
*
* @return array
*/
public function getFlatMessages()
{
$messages = [];
$detailMessages = $this->getDetailMessages();

foreach ($detailMessages as $field => $rules) {
foreach ($rules as $rule => $options) {
foreach ($options as $name => $message) {
$messages[$field . '-' . $rule . '-' . $name] = $message;
}
}
}
return $messages;
}

/**
* Returns summary invalid messages
*
Expand Down
20 changes: 20 additions & 0 deletions tests/unit/ValidatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -586,6 +586,26 @@ public function testGetFirstMessage()
$this->assertEquals('error message 1', $firstMessage);
}

public function testGetFlatMessages()
{
$validator = $this->validate([
'data' => [],
'rules' => [
'name' => 'required',
'email' => 'required',
],
'messages' => [
'name' => 'error message 1',
'email' => 'error message 2',
],
]);
$messages = $validator->getFlatMessages();
$this->assertSame([
'name-required-required' => 'error message 1',
'email-required-required' => 'error message 2',
], $messages);
}

public function testGetRuleValidator()
{
$validator = $this->validate([
Expand Down

0 comments on commit 023b60b

Please sign in to comment.