Say you have a custom rule like this:
<?php
class CheckFoo extends \Respect\Validation\Rules\AbstractRule
{
public function validate($input)
{
if ($input == 'foo')
return true;
else
return false;
}
}
class CheckFooException extends \Respect\Validation\Exceptions\ValidationException
{
public static $defaultTemplates = [
self::MODE_DEFAULT => [
self::STANDARD => '{{name}} must be foo',
],
self::MODE_NEGATIVE => [
self::STANDARD => '{{name}} must not be foo',
],
];
}
This works fine but is it possible to add additional rules inside this rule? To illustrate, is something like this possible:
class CheckFoo extends \Respect\Validation\Rules\AbstractRule
{
public function validate($input)
{
if (strlen($input) != 3)
return false;
if ($input == 'foo')
return true;
else
return false;
}
}
How can I define a custom error message inside CheckFooException
if (strlen($input) != 3)
is triggered?
Inspecting the library you are using, especially the ValidationException class and the implementation for
AttributeException
, it should be possible to access a property declared on your rule class during validation viaValidationException::getParam($propertyName)
from your Exception class. Like so:Then access it implementing/overriding the method
ValidationException::chooseTemplate
, like so:Test:
Alternatively, you could combine 2 different rules with dedicated messages (or, for sth. trivial as length, use the one provided by the library already).