我想验证title_clean
是否是唯一的,可以用作URL的标识符。但它只是通过输入给出的真实公共变量的临时实例(此处为 REST)。
所以我尝试了以下内容:
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));
}
未经测试。我希望这是正确的。