CakePHP 自定义验证规则会导致多个字段出现错误消息


CakePHP custom validation rule causes error message on multiple fields

我的模型中有一些自定义验证函数。例如,在某些字段中,我有一个验证规则,用于检查是否有任何HTML是文本。我的问题是,当我在两个字段上使用相同的验证规则时,视图中的错误消息会显示在两个字段上,即使只有一个失败的验证失败。

前任:

    'field1' => array(
        'noTags' => array(
            'rule' => array( 'detectTags' ),
            'message' => 'HTML tags are not allowed.'
        )
    ),
    'field2' => array(
        'noTags' => array(
            'rule' => array( 'detectTags' ),
            'message' => 'HTML tags are not allowed.'
        )
    ),
...
public function detectTags($check) {
    $value = array_values($check);
    $string = $value[0];
    return ($string == strip_tags($string)); 
}

我已经有一个解决方法(见下文)。我为每个字段使用唯一函数包装验证规则,一切正常。但这很烦人。我怀疑有更好的方法。这是什么?

    'field1' => array(
        'noTags' => array(
            'rule' => array( 'detectTags1' ),
            'message' => 'HTML tags are not allowed.'
        )
    ),
    'field2' => array(
        'noTags' => array(
            'rule' => array( 'detectTags2' ),
            'message' => 'HTML tags are not allowed.'
        )
    ),
...
public function detectTags1($check) {
    return $this->_detectTags($check);
}
public function detectTags2($check) {
    return $this->_detectTags($check);
}
private function _detectTags($check) {
    $value = array_values($check);
    $string = $value[0];
    return ($string == strip_tags($string)); 
}

试试这个

    'field1' => array(
        'noTags1' => array(
            'rule' => array( 'detectTags' ),
            'message' => 'HTML tags are not allowed.'
        )
    ),
    'field2' => array(
        'noTags2' => array(
            'rule' => array( 'detectTags' ),
            'message' => 'HTML tags are not allowed.'
        )
    ),