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

Php 模型规则的Yii2临时验证变量,php,validation,model,yii2,rules,Php,Validation,Model,Yii2,Rules,我想验证title\u clean是否唯一,是否可以用作URL的标识符。但它只是通过输入提供的真实公共变量的临时实例(此处休息) 因此,我尝试了以下方法: public $title; public $title_clean // not set through a form it shall be temporary public function rules() { return [ ['title_clean', 'default', 'value' =>

我想验证
title\u clean
是否唯一,是否可以用作URL的标识符。但它只是通过输入提供的真实公共变量的临时实例(此处休息)

因此,我尝试了以下方法:

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.
}

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

内联验证是您的问题。根据第二条规则,您需要如下验证方法:

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));
}

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

这是rules()方法的一部分吗??您不能将这样的变量添加到规则中,规则仅适用于模型字段(属于db的一部分)。是的,它是rules方法的一部分。数据库中还有一个字段用于
title\u clean
。我只是不想用发送到模型的额外参数获取它。我想动态地为db的字段
title\u clean
生成内容。那么你找错地方了。最好是修改控制器的create方法
actionCreate()
,并在那里添加此字段?第二条规则中的“clean”是什么?一个模型方法,一个类?“不验证”是什么意思?您是否收到验证错误?如果在db中也存在title_clean,那么它真的是临时的吗?请你把事情说清楚并更新你的帖子好吗?我更新了。规则成功,因为没有通过临时验证设置
title\u clean
。所以在第一个:他说可以默认,在第二个:可以清理,在第三个:是的,db中不存在空的
title\u clean
。数据库中没有条目。此脚本只进行插入,并且
标题\u clean
是填充数据库的活动记录的一部分