如何在Kohana 3.1中应用“匹配”验证规则?

问题描述

| 我需要知道如何在Kohana 3.1中应用“匹配”验证规则。我在模型中尝试了以下规则,但没有成功:
\'password_confirm\' => array(
    array(\'matches\',array(\':validation\',\':field\',\'password\')),)
但是它总是失败。我在Valid :: matches()方法的第一行添加一个“ 1”。我将其粘贴在下面:
/**
 * Checks if a field matches the value of another field.
 *
 * @param   array    array of values
 * @param   string   field name
 * @param   string   field name to match
 * @return  boolean
 */
public static function matches($array,$field,$match)
{
    var_dump($array);exit;
    return ($array[$field] === $array[$match]);
}
它打印类型为Validation的对象,如果我执行
var_dump($array[$field])
,则打印
null
。 非常感谢。 更新:我还通过验证消息发现,规则参数的顺序应与此相反:
\'password_confirm\' => array(
    array(\'matches\',\'password\',\':field\')),)
    

解决方法

您的语法是正确的,但是我要猜​​测,您的数据库架构没有\'password_confirm \'列,因此您尝试将规则添加到不存在的字段中。 无论如何,执行密码确认匹配验证的正确位置不在您的模型中,而是在您尝试保存时传递给控制器​​中模型的额外验证。 将其放在您的用户控制器中:
$user = ORM::Factory(\'user\');

// Don\'t forget security,make sure you sanitize the $_POST data as needed
$user->values($_POST);

// Validate any other settings submitted
$extra_validation = Validation::factory(
    array(\'password\' => Arr::get($_POST,\'password\'),\'password_confirm\' => Arr::get($_POST,\'password_confirm\'))
    );

$extra_validation->rule(\'password_confirm\',\'matches\',array(\':validation\',\'password_confirm\',\'password\'));

try 
{
    $user->save($extra_validation);
    // success
}
catch (ORM_Validation_Exception $e)
{               
   $errors = $e->errors(\'my_error_msgs\');
   // failure
}
另外,请参阅Kohana 3.1 ORM验证文档以获取更多信息