问题
I need to know how to apply the "matches" validation rule in Kohana 3.1. I've tried the following rule in my model with no success:
'password_confirm' => array(
array('matches', array(':validation', ':field', 'password')),
)
But it always fails. I put a var_dump($array)
in the first line of the Valid::matches() method. I paste it below:
/**
* 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]);
}
It prints an object of type Validation and if I do var_dump($array[$field])
it prints null
.
Thanks a lot in advance.
UPDATE: Also I figured out by the validation message that the order of the parameters of the rule should be inverted to this:
'password_confirm' => array(
array('matches', array(':validation', 'password', ':field')),
)
回答1:
Your syntax is correct, but I'm going to guess and say that your DB schema does not have a 'password_confirm' column so you are trying to add a rule to a field that doesn't exist.
Regardless, the right place to perform password confirm matching validation is not in your model but as extra validation that is passed to your model in your controller when you attempt to save.
Put this in your user controller:
$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
}
Also, see the Kohana 3.1 ORM Validation documentation for more information
来源:https://stackoverflow.com/questions/6143681/how-to-apply-the-matches-validation-rule-in-kohana-3-1