简体   繁体   English

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

[英]Yii2 temporary validation variable for model rules

I want to validate that title_clean is unique and can be used as an identifier for URL's. 我想验证title_clean是唯一的,并且可以用作URL的标识符。 But it is just an temporary instance of the real public variable that is given through the input (REST here). 但这只是通过输入(此处为REST)给出的实际公共变量的临时实例。

So I tried it with the following: 所以我尝试了以下方法:

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

but it does not validate neither throw out an error. 但是它既不验证也不抛出错误。 Does anyone has an idea about it? 有人对此有想法吗?

The inline validation is your problem. 内联验证是您的问题。 According to documentation for your second rule you would need a validating method like this: 根据第二条规则的文档 ,您将需要这样的验证方法:

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

and the clean method: 和清洁方法:

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

Untested. 未经测试。 I hope this is correct. 我希望这是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM