CodeIgniter 3.1.9表单验证

时间:2018-12-08 11:20:55

标签: codeigniter validation validationrules reserved

我对CI中的表单验证有疑问。 规则似乎不调用函数 我的代码如下:

[...]    
$this->form_validation->set_rules('last_name', 'last name','trim|required|min_length[3]|max_length[30]|callback_reserved',
    [
        'required'      => 'The %s is missed',
        'min_length'    => 'The %s must contain at least %s letters',
        'max_length'    => 'The %s must contain at max %s letters',
    ]);
[...]

function reserved($str) {
    $reserved = ['aaaa','bbbb','cccc','dddd'];
    if (in_array(strtolower($str), $reserved)) {
        $this->form_validation->set_message('reserved', 'The {field} '.$str.' is reserved');
        return false;
    } else {
        return true;
    }
}

1 个答案:

答案 0 :(得分:0)

这是创建自定义验证规则的更好方法:

$config = array(
    'field'     => 'last_name',
    'label'     => 'last name',
    'rules'     => array('trim', 'required', array('last_name_is_reserved',
        function($str)
        {
            $reserved = ['aaaa','bbbb','cccc','dddd'];
            return (in_array(strtolower($str), $reserved)) ? TRUE : FALSE;
        }),
    ),
    'errors' => array(
        'last_name_is_reserved' => 'The {field} field is reserved.',
    ),
);
$this->form_validation->set_rules($config);