2011-05-26 72 views
2

我需要知道如何应用Kohana 3.1中的“匹配”验证规则。我在我的模型中试过以下规则并没有成功:如何应用Kohana 3.1中的“匹配”验证规则?

'password_confirm' => array(
    array('matches', array(':validation', ':field', 'password')), 
) 

但它总是失败。我把一个var_dump($array)放在Valid :: matches()方法的第一行。我粘贴如下:

/** 
* 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]); 
} 

它打印类型的验证对象,如果我做var_dump($array[$field])它打印null

非常感谢。

UPDATE:我也想通了由规则的参数的顺序应该颠倒此验证消息:

'password_confirm' => array(
    array('matches', array(':validation', 'password', ':field')), 
) 

回答

4

你的语法是正确的,但我要猜并且说你的数据库模式没有'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 Validation documentation以获取更多信息

+0

非常感谢您的回答,它的工作不错。 – 2011-05-27 20:24:56