Yii2 模型规则的临时验证变量

Yii2 temporary validation variable for model rules

我想验证 title_clean 是唯一的并且可以用作 URL 的标识符。但它只是通过输入(此处为 REST)给出的真实 public 变量的临时实例。

所以我尝试了以下方法:

public $title;
public $title_clean // not set through a form it shall be temporary

public function rules()
{
    return [
        ['title_clean', 'default', 'value' => $this->title],
        ['title_clean', 'clean'],
        ['title_clean', 'unique', 'targetClass' => 'Jobs', 'targetAttribute' => 'title_clean', 'message' => 'The title was already taken.'],
        [...]
    ];
}

 /**
 * Cleaning Method
 *
 * @return mixed|string
 */
private function clean()
{
    $args = func_get_args();
    foreach($args as $string) {
        $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
        $specials = array("/ä/","/ö/","/ü/","/Ä/","/Ö/","/Ü/","/ß/");
        $replace = array("ae","oe","ue","Ae","Oe","Ue","ss");
        if (empty($clean)) {
            $clean = preg_replace('/[^A-Za-z0-9\-]/', '', preg_replace($specials, $replace, $string));
        } else {
            $clean .= preg_replace('/[^A-Za-z0-9\-]/', '', preg_replace($specials, $replace, $string));
        }
    }
    return $clean; // Removes special chars.
}

但它不验证也不抛出错误。有人对此有想法吗?

内联验证是您的问题。根据 documentation 你的第二条规则,你需要这样的验证方法:

public function clean($attribute, $params)
{
    $this->$attribute = self::do_the_clean_up_things($value);
}

和清理方法:

private static function do_the_clean_up_things($string)
{
    $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
    $specials = array("/ä/","/ö/","/ü/","/Ä/","/Ö/","/Ü/","/ß/");
    $replace = array("ae","oe","ue","Ae","Oe","Ue","ss");
    return preg_replace('/[^A-Za-z0-9\-]/', '', preg_replace($specials, $replace, $string));
}

未经测试。我希望这是正确的。