2011-05-26 67 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