Skip to content

Commit

Permalink
Add custom errors field/rule
Browse files Browse the repository at this point in the history
  • Loading branch information
filisko committed Mar 9, 2020
1 parent 3d0223c commit 337b03d
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 7 deletions.
16 changes: 9 additions & 7 deletions gump.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@ public static function get_instance()

public static $rules_parameters_arrays_delimiter = ';';


// ** ------------------------- Validation Data ------------------------------- ** //

public static $basic_tags = '<br><p><a><strong><b><i><em><img><blockquote><code><dd><dl><hr><h1><h2><h3><h4><h5><h6><label><ul><li><span><sub><sup>';
Expand All @@ -83,6 +82,8 @@ public static function get_instance()

protected $lang;

protected $custom_messages = [];


// ** ------------------------- Validation Helpers ---------------------------- ** //

Expand Down Expand Up @@ -376,16 +377,16 @@ public function errors()
* Perform data validation against the provided ruleset.
* If any rule's parameter contains either '|' or ',', the corresponding default separator can be changed
*
* @param mixed $input
* @param array $ruleset
*
* @param mixed $input
* @param array $ruleset
* @param array $custom_messages
* @return mixed
*
* @throws Exception
*/
public function validate(array $input, array $ruleset)
public function validate(array $input, array $ruleset, array $custom_messages = [])
{
$this->errors = [];
$this->custom_messages = $custom_messages;

foreach ($ruleset as $field => $rawRules) {
$input[$field] = $input[$field] ?? null;
Expand Down Expand Up @@ -694,7 +695,8 @@ public function get_errors_array(bool $convert_to_string = false)
throw new Exception('Rule "'.$e['rule'].'" does not have an error message');
}

$result[$e['field']] = $this->process_error_message($e['field'], $e['param'], $messages[$e['rule']]);
$message = $this->custom_messages[$e['field']][str_replace('validate_', '', $e['rule'])] ?? $messages[$e['rule']];
$result[$e['field']] = $this->process_error_message($e['field'], $e['param'], $message);
}

return $result;
Expand Down
18 changes: 18 additions & 0 deletions tests/GetErrorsArrayTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -137,4 +137,22 @@ public function testItThrowsExceptionWhenCustomValidatorFailsWithoutAnErrorMessa

$this->gump->get_errors_array();
}

public function testCustomErrorMessages()
{
$this->gump->validate([
'test_number' => '123'
], [
'test_number' => 'required|between_len,1;2'
], [
'test_number' => [
'required' => 'Test Number can not be empty. Please fill it up.',
'between_len' => '{field} length MUST be between {param[0]} and {param[1]} !!!'
]
]);

$this->assertEquals([
'test_number' => 'Test Number length MUST be between 1 and 2 !!!'
], $this->gump->get_errors_array());
}
}

0 comments on commit 337b03d

Please sign in to comment.