Codeigniter 2的自定义表单验证错误消息

时间:2011-04-30 03:39:38

标签: php codeigniter validation

我有一个名为“business_id”的下拉列表。

<select name="business_id"> 
    <option value="0">Select Business</option> More options... 
</select>

验证规则,用户必须选择一个选项。

$this->form_validation->set_rules('business_id', 'Business', 'greater_than[0]');

出现错误信息的问题是:业务字段必须包含大于0的数字。不是很直观!我希望它说“你必须选择一个企业”。

我试过了:

$this->form_validation->set_message('Business', 'You must select a business');

但CI完全忽略了这一点。有人有解决方案吗?

10 个答案:

答案 0 :(得分:7)

我有同样的要求添加custom form validation error messages in codeigniter 2(例如“您必须同意我们的条款和条件”)。当然,覆盖require和greater_than的错误消息是错误的,因为它会错误地为表单的其余部分生成消息。我扩展了CI_Form_validation类并重写了set_rules方法以接受新的'message'参数:

<?php

class MY_Form_validation extends CI_Form_validation
{
    private $_custom_field_errors = array();

    public function _execute($row, $rules, $postdata = NULL, $cycles = 0)
    {
        // Execute the parent method from CI_Form_validation.
        parent::_execute($row, $rules, $postdata, $cycles);

        // Override any error messages for the current field.
        if (isset($this->_error_array[$row['field']])
            && isset($this->_custom_field_errors[$row['field']]))
        {
            $message = str_replace(
                '%s',
                !empty($row['label']) ? $row['label'] : $row['field'],
                $this->_custom_field_errors[$row['field']]);

            $this->_error_array[$row['field']] = $message;
            $this->_field_data[$row['field']]['error'] = $message;
        }
    }

    public function set_rules($field, $label = '', $rules = '', $message = '')
    {
        $rules = parent::set_rules($field, $label, $rules);

        if (!empty($message))
        {
            $this->_custom_field_errors[$field] = $message;
        }

        return $rules;
    }
}

?>

使用上面的类,您将使用如下自定义错误消息生成规则:

$this->form_validation->set_rules('business_id', 'Business', 'greater_than[0]', 'You must select a business');

您也可以在自定义消息中使用'%s',它会自动填写fieldname的标签。

答案 1 :(得分:6)

如果您想自定义每条规则显示的错误消息,可以在以下位置的数组中找到它们:

/system/language/english/form_validation_lang.php

答案 2 :(得分:3)

尝试不在默认选择...

上设置value属性
<select name="business_id"> 
    <option value>Select Business</option> More options... 
</select>   

然后只使用表单验证规则所需的...

$this->form_validation->set_rules('business_id', 'Business', 'required'); 

我想你可以尝试编辑你尝试设置信息的方式......

$this->form_validation->set_message('business_id', 'You must select a business');
instead of
$this->form_validation->set_message('Business', 'You must select a business');

我不完全确定这是否可以解决问题。

答案 3 :(得分:1)

你应该像Anthony说的那样扩展Form_validation库。

例如,我在名为MY_Form_validation.php的文件中执行此类操作,该文件应放在/application/libraries

function has_selection($value, $params)
{
    $CI =& get_instance();

    $CI->form_validation->set_message('has_selection', 'The %s need to be selected.');

    if ($value == -1) {
        return false;
    } else {
        return true;
    }
}

在您的情况下,因为您的第一个选项(指导选项 - 请选择...)的值为0,您可能需要将条件语句从-1更改为0 }。然后,从现在开始,您可以使用此行来检查选择值:

$this->form_validation->set_rules('business_id', 'Business', 'has_selection');

希望这有帮助!

答案 4 :(得分:1)

这是我使用的一个简单的CI2回调函数。我想要的不仅仅是“必需”作为验证的默认参数。文档有助于:http://codeigniter.com/user_guide/libraries/form_validation.html#callbacks

    public function My_form() {

        ...Standard CI validation stuff...
        $this->form_validation->set_rules('business_id', 'Business', 'callback_busid');
        ...

        if ($this->form_validation->run() == FALSE) {
            return false; 
    }
    else {
        ...process the form...
        $this->email->send();
        }
    } // Close My_form method

    // Callback method
    function busid($str) {

        if ($str == '') {
        $this->form_validation->set_message('business_id', 'Choose a business, Mang!');
        return FALSE;
    }
    else {
        return TRUE;
    }
         } // Close the callback method

对于您的情况,您可以更改回调以检查if($str<0) - 我假设您在选择/下拉菜单中使用过数字。

如果回调返回false,则保留表单并显示错误消息。否则,它会被传递并发送到form method的“其他”。

答案 5 :(得分:1)

一点点黑客可能对你不利,但我做了一点改变。

实施例, 我想更改消息'电子邮件字段必须是唯一值'。

我这样做了

<?php
$error = form_error('email');
echo str_replace('field must be a unique value', 'is already in use.', $error); 
// str_replace('string to search/compare', 'string to replace with', 'string to search in')
?>

如果找到字符串,则会打印我们的自定义消息,否则会显示错误消息,因为它类似于“电子邮件字段必须是有效的电子邮件”等...

答案 6 :(得分:1)

对于那些使用CodeIgniter 3的人,您可以执行以下操作:

$this->form_validation->set_rules('business_id', 'Business', 'greater_than[0]', array(
'greater_than' => 'You must select a business',
));

如果您正在使用CodeIgniter 2,则需要使用新的CodeIgniter 3 CI_Form_validation类扩展并覆盖CI_Form_validation类(https://ellislab.com/codeigniter/user-guide/general/creating_libraries.html以获取有关如何执行此操作的更多信息)并使用上述函数。 / p>

答案 7 :(得分:1)

规则的名称是最后一个参数。

请尝试:

$this->form_validation->set_message('greater_than[0]', 'You must select a business');

更多信息: https://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#validationrules

答案 8 :(得分:0)

我使用一个简单的函数扩展了form_validation库,确保下拉框没有选择其默认值。希望这可以帮助。

<强>应用/库/ MY_Form_validation.php

<?php if (!defined('BASEPATH')) exit('No direct script access allowed.');

class MY_Form_validation extends CI_Form_validation {

    function __construct()
    {
        parent::__construct();
        $this->CI->lang->load('MY_form_validation');
    }

     /**
     * Make sure a drop down field doesn't have its default value selected.
     *
     * @access  public
     * @param   string
     * @param   field
     * @return  bool
     * @author  zechdc
     */
    function require_dropdown($str, $string_to_compare)
    {   
        return ($str == $string_to_compare) ? FALSE : TRUE;
    }
}

<强>应用/语言/英语/ MY_Form_validation_lang.php

$lang['require_dropdown']   = 'The %s field must have an item selected.';

如何使用:

1)制作表格下拉框:

<select name="business_id"> 
    <option value="select">Select Business</option> More options... 
</select>

2)创建验证规则。您可以将值设置为0并使用require_dropdown [0],但我从未尝试过。

$this->form_validation->set_rules('business_id', 'Business', 'require_dropdown[select]');

3)设置自定义消息:(或跳过此步骤并使用语言文件中的一个。)

$this->form_validation->set_message('business_id', 'You must select a business');

答案 9 :(得分:0)

创建方法username_check回调函数

01

public function username_check($str)
{
    if ($str=="")
    {
        $this->form_validation->set_message('username_check', 'Merci d’indiquer le nombre d’adultes');
        return FALSE;
    }
    else
    {
        return TRUE;
    }
}

- 02.然后将此验证码放在您的班级

$this->form_validation->set_rules('number_adults', 'Label Name','Your Message',) 'callback_username_check');

这可能对您有所帮助