尊重\验证中的自定义规则中有多个规则/错误消息?

时间:2018-11-18 18:11:33

标签: php validation respect-validation

假设您有一个这样的自定义规则:

var3

这很好,但是可以在此规则内添加其他规则吗?为了说明这一点,这是可能的:

<?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',
        ],
    ];
}

如果触发了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; } } ,如何在CheckFooException内定义自定义错误消息?

1 个答案:

答案 0 :(得分:1)

检查您正在使用的库,尤其是ValidationException类和AttributeException的实现,应该可以在验证过程中通过ValidationException::getParam($propertyName)从您的规则类中访问在规则类上声明的属性,您的Exception类。像这样:

class CheckFoo extends \Respect\Validation\Rules\AbstractRule
{
    public $reason;

    public function validate($input)
    {
        if (strlen($input) != 3) {
            $this->reason = 'length';
            return false;
        }

        if ($input !== 'foo') {
            $this->reason = 'content';
            return false;
        }
        return true;

    }
}

然后访问它,以实现/重写方法ValidationException::chooseTemplate,如下所示:

class CheckFooException extends \Respect\Validation\Exceptions\ValidationException
{
    const INVALID_LENGTH = 0;
    const INVALID_NAME = 1;

    public static $defaultTemplates = [
        self::MODE_DEFAULT => [
            self::INVALID_NAME => '{{name}} must be foo',
            self::INVALID_LENGTH => '{{name}} must be 3 characters long',
        ],
        self::MODE_NEGATIVE => [
            self::INVALID_NAME => '{{name}} must not be foo',
            self::INVALID_LENGTH => '{{name}} must not be 3 characters long',
        ],
    ];

    public function chooseTemplate()
    {
        return 'length' === $this->getParam('reason')
            ? self::INVALID_LENGTH
            : self::INVALID_NAME;
    }
}

测试:

v::checkFoo()->check('FOO'); // => "FOO" must be foo
v::checkFoo()->check('foox'); // => "foox" must be 3 characters long

或者,您可以将2条不同的规则与专用消息组合在一起(或者,就长度而言,琐碎的事,请使用已经由库提供的规则)。