簡體   English   中英

Codeigniter 2 的自定義表單驗證錯誤消息

[英]Custom form validation error message for Codeigniter 2

我有一個名為“business_id”的下拉菜單。

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

驗證規則來了,用戶必須選擇 select 選項。

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

問題是錯誤消息說:業務字段必須包含一個大於 0 的數字。不是很直觀。 我想讓它說“你必須 select 一個企業”。

我試過了:

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

但是 CI 完全忽略了這一點。 有人對此有解決方案嗎?

我對在 codeigniter 2 中添加自定義表單驗證錯誤消息有相同的要求(例如“您必須同意我們的條款和條件”)。 當然,覆蓋 require 和 greater_than 的錯誤消息是錯誤的,因為它會錯誤地為表單的 rest 生成消息。 我擴展了 CI_Form_validation class 並覆蓋了 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;
    }
}

?>

使用上面的 class 您將生成帶有自定義錯誤消息的規則,如下所示:

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

您也可以在自定義消息中使用“%s”,它將自動填寫字段名的 label。

如果您想自定義與每個規則一起顯示的錯誤消息,您可以在數組中找到它們:

/system/language/english/form_validation_lang.php

盡量不要在默認的select上設置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');

我不完全確定這是否會奏效。

一個小技巧可能對你不利,但我做了一點改變。

例如,我想更改消息“Email 字段必須是唯一值”。

我已經這樣做了

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

如果找到字符串,則它會打印我們的自定義消息,否則它將顯示錯誤消息,就像“Email 字段必須是有效的電子郵件”等...

對於那些在 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.html for more info on how to do so) with the new CodeIgniter 3 CI_Form_validation class 並使用上面的 function。

規則的名稱是最后一個參數。

請試試:

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

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

您應該像 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;
    }
}

在您的情況下,因為您的第一個選項(指導選項 - 請 select...)的值為0 ,您可能希望將條件語句從-1更改為0 然后,從現在開始,您可以使用這一行來檢查選擇值:

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

希望這可以幫助!

這是我使用的一個簡單的 CI2 回調 function。 我想要的不僅僅是“必需”作為驗證的默認參數。 該文檔有幫助: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的“else”。

創建方法 username_check 回調 function

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. 然后把這個驗證碼放在你的 class

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

這可能會幫助你

我用一個簡單的 function 擴展了 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');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM