我想验证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.
}
但它不验证既不抛出错误。有没有人对此有所了解?
答案 0 :(得分:1)
内联验证是您的问题。根据你的第二条规则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));
}
未测试。我希望这是正确的。