Custom form validation error message for Codeignit

2019-01-26 14:22发布

问题:

I have a drop down named "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".

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?

回答1:

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

<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.



回答2:

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:

<?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.



回答3:

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


回答4:

You should extend the Form_validation library as Anthony said.

For instance, I do something like this in a file called MY_Form_validation.php which should be put on /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 -1 to 0. Then, from now on, you could have this line to check selection value:

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

Hope this helps!



回答5:

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

    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 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.



回答6:

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...



回答7:

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

$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 and use the function above.



回答8:

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



回答9:

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.

application/libraries/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

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

How to Use:

1) Make your form drop down box:

<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.

$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.)

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


回答10:

Create Method username_check call back 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. Then Put this Validation Code on your class

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

This may help you