使用CodeIgniter表单验证的自定义错误消息

时间:2013-01-22 14:15:42

标签: php forms codeigniter validation

我想在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]');
}

7 个答案:

答案 0 :(得分:21)

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

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

因此,只有我们才能收到"This Username is already taken""This Email is already taken"等消息。

答案 1 :(得分:2)

这对我有用

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

答案 2 :(得分:2)

你最好这样使用:

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

form_validation使用为该字段设置的标签更改%s

希望这有帮助!

答案 3 :(得分:1)

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

$this->form_validation->set_rules('username','Username','is_unique',array('is_unique' => 'The %s is already taken'));

答案 4 :(得分: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变量后,将其打印在您的视图上。

答案 5 :(得分:0)

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

答案 6 :(得分:-1)

您需要参考字段的名称而不是规则。

文档稍有混淆,因为它们也将其命名为“必需”。

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

应该是

$this->form_validation->set_message('username', 'The username is already taken');

希望这有帮助!