Kohana 3.1国家验证回调

时间:2011-06-15 22:50:25

标签: validation callback kohana

我正在尝试在我的网站上设置注册功能,我需要验证用户输入的选择类型的国家/地区:

public function rules()
    {
        return array(
            ......
            'country' => array(
                array('not_empty'),
                array('digit'),
                array(array($this, 'country_from_list'), array(':validation', ':field'))
            ),
            ......
        );
    }

这是我的回调:

public static function country_from_list($values)
{
    // array id => value
    $countries = ORM::factory('country')->getActive('array');

    return Validation::factory($values)
        ->rule('country', 'in_array', array(':value', $countries));
}

但它不起作用。有任何想法吗?我正试图从Kohana 3.0.9移植它......

2 个答案:

答案 0 :(得分:0)

有一个问题(至少)。以下内容:

array(':value', $countries)

实际上是一个数组,其中:

  • 第一个元素是:value字符串,
  • 第二个元素是ORM::factory('country')->getActive('array')
  • 的结果

但我不是Kohana 3.1验证的专家 - 我听说自3.0以来它已经发生了变化。

答案 1 :(得分:0)

如果您将Validation对象传递给回调方法,则可以在条件失败时对其执行自定义错误。 (在你的回调中:$ validation->错误(...))

否则,你的回调应该接受字段的值,返回bool并看起来像这样:

// The callback method is static, you shouldn't call it on the instance.
array(array('Model_Whatever::country_from_list'), array(':value'))

方法:

public static function country_from_list($value)
{
    return in_array($value, ORM::factory('country')->getActive('array'));
}