【问题标题】:Yii2 temporary validation variable for model rulesYii2 模型规则的临时验证变量
【发布时间】:2015-07-05 16:56:58
【问题描述】:

我想验证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.
}

但它不会验证也不会抛出错误。有人知道吗?

【问题讨论】:

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

标签: php validation model yii2 rules


【解决方案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));
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-03
    • 2015-09-05
    • 1970-01-01
    • 2018-02-22
    • 1970-01-01
    相关资源
    最近更新 更多