14

我想在我的 CodeIgniter 表单中制作一些自定义错误消息。我试过使用

$this->form_validation->set_message('is_unique[users.username]', 'The username is already taken');

但是我无法让它工作。

编辑form_validation_lang.php文件还不够好,因为is_unique用户名已经被用作用户名,并且电子邮件已经为邮件注册。

如何制作此自定义错误消息?

这是我的代码片段:

$this->form_validation->set_message('is_unique[users.username]', 'The username is already taken');

// Check if username has changed
if ($this->input->post('username') !== $user->username) {
    $this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[4]|max_length[20]|is_unique[users.username]');
}
4

7 回答 7

33

这样做的正确方法是传递字符串格式

$this->form_validation->set_message('is_unique', 'The %s is already taken');

所以,只有我们才能得到类似"This Username is already taken"or的消息"This Email is already taken"

于 2014-03-17T17:45:25.800 回答
5

这是您仅为用户名设置消息错误的方式:

$this->form_validation->set_rules('username','Username','is_unique',array('is_unique' => 'The %s is already taken'));
于 2019-02-05T10:54:59.263 回答
2

这对我有用

$this->form_validation->set_message('is_unique', 'The username is already taken');
于 2013-04-19T07:57:27.953 回答
2

最好像这样使用:

$this->form_validation->set_message('is_unique', 'The %s is already taken');

form_validation 随%s为字段设置的标签而变化。

希望这可以帮助!

于 2014-04-30T16:52:39.220 回答
2
create a **form_validation.php** file and use this method:

"add_user_rule"   => [
    [
        "field" => "username",
        "label" => "Username",
        "rules" => "required|trim|is_unique[users.username]",
        "errors" => [
            'is_unique' => 'The %s is already taken.',
        ],
    ],
],

Thank You
于 2019-04-10T06:03:44.543 回答
0

您可以validation_errors()在使用检查验证后将自定义消息添加到字符串$this->form_validation->run() == true

if(YOUR_CONDITION){
   $this->form_validation->run();
   $err = validation_errors();
   $err = $err. '<p>Custom validation error message</p>'. PHP_EOL;
   $data['err'] = $err;
   $this->load->view('viewname', $data);
}
else if ($this->form_validation->run() == true ) {
        #code...
}
else..

将您的自定义消息设置为$err变量后,将其打印在您的视图上。

于 2017-12-26T10:21:02.797 回答
0

您可以传递第三个参数来设置验证消息

$this->form_validation->set_rules(
        'username', 'Username',
        'required|min_length[5]|max_length[12]|is_unique[users.username]',
        array(
                'required'      => 'You have not provided %s.',
                'is_unique'     => 'This %s already exists.'
        )
);

在这里检查

于 2021-12-03T04:52:39.763 回答