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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5839327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:38:38  来源:igfitidea点击:

Custom form validation error message for Codeigniter 2

phpcodeignitervalidation

提问by pigfox

I have a drop down named "business_id".

我有一个名为“business_id”的下拉菜单。

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

Here comes the validation rule, user must select an option.

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

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

Problem being the error message says: The Business field must contain a number greater than 0. Not very intuitive! I want it to say "You must select a business".

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

I tried:

我试过:

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

But CI complete ignores this. Does anyone have a solution for this?

但是 CI Complete 忽略了这一点。有没有人对此有解决方案?

采纳答案by Anthony Hyman

Try not setting the value attribute on the default select...

尽量不要在默认选择上设置 value 属性...

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

and then just using required for your form validation rule...

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

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

I suppose you could try editing the way that you're trying to set the message also...

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

$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');

I'm not entirely sure if that will do the trick though.

我不完全确定这是否会奏效。

回答by Andrew Mackrodt

I had the same requirement for adding custom form validation error messages in codeigniter 2(e.g. "You must agree to our Terms & Conditions"). Naturally it would be wrong to override the error messages for require and greater_than as it would erroneously produce messages for the rest of the form. I extended the CI_Form_validation class and have overridden the set_rules method to accept a new 'message' parameter:

我对在 codeigniter 2 中添加自定义表单验证错误消息有同样的要求(例如“您必须同意我们的条款和条件”)。当然,覆盖 require 和 Greater_than 的错误消息是错误的,因为它会错误地为表单的其余部分生成消息。我扩展了 CI_Form_validation 类并覆盖了 set_rules 方法以接受新的“消息”参数:

<?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;
    }
}

?>

With the above class you would produce your rule with a custom error message like so:

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

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

You may also use '%s' in your custom message which will automatically fill in the label of fieldname.

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

回答by misterchristos

If you'd like to customize the error messages that are displayed with each rule, you can find them in an array at:

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

/system/language/english/form_validation_lang.php

回答by Ngoc Pham

You should extend the Form_validation library as Anthony said.

您应该像安东尼所说的那样扩展 Form_validation 库。

For instance, I do something like this in a file called MY_Form_validation.phpwhich should be put on /application/libraries

例如,我在一个名为的文件中做这样的事情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;
    }
}

In your case, because your first option (Guidance option - Please select ...) has the value of 0, you may want to change the conditional statement from -1to 0. Then, from now on, you could have this line to check selection value:

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

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

Hope this helps!

希望这可以帮助!

回答by Dawson

Here's a simple CI2 callback function that I used. I wanted something other than just 'required' as a default param of the validation. The documentation helps: http://codeigniter.com/user_guide/libraries/form_validation.html#callbacks

这是我使用的一个简单的 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

For your case you could change the callback to check for if($str<0)- I'm assuming you've used numbers in your selection/dropdown menu.

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

If the callback returns false, the form is held and the error message is shown. Otherwise, it's passed and sent to the 'else' of the form method.

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

回答by Waqleh

for those of you working on CodeIgniter 3 you can do the following:

对于那些在 CodeIgniter 3 上工作的人,您可以执行以下操作:

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

And if you are using CodeIgniter 2, you will need to extend and override the CI_Form_validation class (https://ellislab.com/codeigniter/user-guide/general/creating_libraries.htmlfor more info on how to do so) with the new CodeIgniter 3 CI_Form_validation class and use the function above.

如果您使用的是 CodeIgniter 2,则需要使用新的扩展和覆盖 CI_Form_validation 类(https://ellislab.com/codeigniter/user-guide/general/creating_libraries.html了解更多信息) CodeIgniter 3 CI_Form_validation 类并使用上面的函数。

回答by Pablo

The name of the rule is the last parameter.

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

Please try:

请尝试:

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

More info: https://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#validationrules

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

回答by Bilal

A little hack might not good for you but I have done this for a little change.

一个小技巧可能对你没有好处,但我这样做是为了一点点改变。

Example, I want to change message 'The Email field must be a unique value'.

例如,我想更改消息“电子邮件字段必须是唯一值”。

I have done this as

我已经这样做了

<?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')
?>

If string found then it prints our custom message else it will display error message as it is like 'The Email field must be a valid email' etc...

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

回答by Sameera

Create Method username_check call back function

创建方法 username_check 回调函数

01.

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. Then Put this Validation Code on your class

-- 02. 然后把这个验证码放在你的班级上

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

This may help you

这可能会帮助你

回答by zechdc

I extended the form_validation library with a simple function that makes sure a drop down box does not have its default value selected. Hope this helps.

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

application/libraries/MY_Form_validation.php

应用程序/库/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;
    }
}

application/language/english/MY_Form_validation_lang.php

应用程序/语言/英语/MY_Form_validation_lang.php

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

How to Use:

如何使用:

1) Make your form drop down box:

1)使您的表单下拉框:

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

2) Create Validation Rule. You might be able to set the value to 0 and use require_dropdown[0] but I've never tried that.

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

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

3) Set your custom message: (Or skip this step and use the one in the language file.)

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

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