Skip to content

Commit fad882b

Browse files
authored
Merge pull request #79 from chadicus/master
Allow value placeholder in custom error messages
2 parents 7a68263 + d0cf5f2 commit fad882b

3 files changed

Lines changed: 24 additions & 3 deletions

File tree

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,8 @@ The filter specification for a single field is also an array. It can contain tw
107107
`defaultRequired` option.
108108
* `default` defines what the default value of this field is if none is given. A field with a default value will be guaranteed to be in the
109109
result. The `required` value does not affect `default` behavior.
110+
* `error` defines a custom error message to be returned if the value fails filtering. Within the error string, `{value}` can be used as a placeholder
111+
for the value that failed filtering.
110112

111113
The rest of the specification for the field are the filters to apply.
112114

src/Filterer.php

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -379,14 +379,13 @@ private static function handleCustomError(
379379
$error = $customError;
380380
if ($error === null) {
381381
$error = sprintf(
382-
"Field '%s' with value '%s' failed filtering, message '%s'",
382+
"Field '%s' with value '{value}' failed filtering, message '%s'",
383383
$field,
384-
trim(var_export($value, true), "'"),
385384
$e->getMessage()
386385
);
387386
}
388387

389-
$errors[] = $error;
388+
$errors[] = str_replace('{value}', trim(var_export($value, true), "'"), $error);
390389
return $errors;
391390
}
392391

tests/FiltererTest.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -417,6 +417,26 @@ public function filterWithCustomError()
417417
);
418418
}
419419

420+
/**
421+
* @test
422+
* @covers ::filter
423+
*/
424+
public function filterWithCustomErrorContainingValuePlaceholder()
425+
{
426+
$result = Filterer::filter(
427+
[
428+
'fieldOne' => [
429+
'error' => "The value '{value}' is invalid.",
430+
['uint'],
431+
],
432+
],
433+
['fieldOne' => 'abc']
434+
);
435+
$this->assertSame(
436+
[false, null, "The value 'abc' is invalid.", []],
437+
$result
438+
);
439+
}
420440
/**
421441
* Verify behavior of filter() when 'error' is not a string value.
422442
*

0 commit comments

Comments
 (0)