首页 文章

如何在CodeIgniter中的表单验证中设置自定义过滤器?

提问于
浏览
2

我正在使用CodeIgniter的form validation . 这是一个例子:

$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');

文件说:

任何接受一个参数的本机PHP函数都可以用作规则,如htmlspecialchars,trim,MD5等 .

如果我希望值通过我自己的自定义过滤器怎么办?例如,我希望清除"badWord"的值 .

function curseWordRemove($original = '') {
    return str_replace('badWord', '', $original);
}

CodeIgniter已经提供了进行自定义验证的方法,但不提供自定义过滤器 . 自定义验证仅返回true或false,而不是过滤后的字符串 .

function isPolite($string = '') {
    if (strpos($string, 'badWord') !== false) {
        $this->form_validation->set_message(
            'fieldName',
            'contains a very bad word'
        );
        return false;
    } else {
        return true;
    }
}

1 回答

  • 4

    Jojo,你一定错过了用户指南,它被称为 callback ,这里是the documentation .

    一个例子:

    <?php
    
    class Form extends CI_Controller {
    
        public function index()
        {
            $this->load->helper(array('form', 'url'));
    
            $this->load->library('form_validation');
    
            $this->form_validation->set_rules('username', 'Username', 'callback_username_check');
            $this->form_validation->set_rules('password', 'Password', 'required');
            $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
            $this->form_validation->set_rules('email', 'Email', 'required|is_unique[users.email]');
    
            if ($this->form_validation->run() == FALSE)
            {
                $this->load->view('myform');
            }
            else
            {
                $this->load->view('formsuccess');
            }
        }
    
        public function username_check($str)
        {
            if ($str == 'test')
            {
                $this->form_validation->set_message('username_check', 'The %s field can not be the word "test"');
                return FALSE;
            }
            else
            {
                return TRUE;
            }
        }
    
    }
    ?>
    

    基本上,在控制器中创建一个名为 callback_check_bad_words 的验证和一个名为 check_bad_words($value) 的匹配函数 . 结果返回一个布尔值(结果返回验证) .

    由于您只能传回一个布尔值,您需要使用全局变量,或者稍后运行单词的“清理”,在验证中不需要它,除非您想要阻止它提交 .

    如果您的目的是清理坏词的输入,只需这样做,不要验证它 .

相关问题