CodeIgniter custom validation errors for each rule per each field

走远了吗. 提交于 2019-12-12 06:55:39

问题


I'm using CodeIngiter 2.1 and I wanna define custom validation errors for each rule per each field. The fields are as follows.

array(
'field' => 'firstname',
'rules' => 'required',
    'error' => 'This field cannot be empty.'
),
array(
'field' => 'email',
'rules' => 'required',
    'error' => 'The email cannot be empty.'
)

But In CodeIgniter only one error message is defined for one rule. So how to override that one and Please suggest some solutions for getting different errors for perticular field. The work is more appreciated.


回答1:


Try using the CI function :

   set_message();

All of the native error messages are located in the following language file:

   language/english/form_validation_lang.php

To set your own custom message you can either edit that file, or use the following function:

   $this->form_validation->set_message('rule', 'Error Message');

for more about set_message here

Hope it will help;




回答2:


I recently made this custom error message option for my codeigniter 3.0-dev applicaiton. Hope this helps anyone out there.

https://gist.github.com/abdmaster/7287962

To use it (example),

$this->form_validation->set_rules('name','Name','required|alpha',array('required' => 'Please fill the field %s .');`

It will work with Base models like jamierumbelow's MY_Model. In your model, you do something like this:

public $validate = array(
  'display_name'  => array(
    'field' => 'display_name',
    'label' => 'Display Name',
    'rules' => 'trim|required|xss_clean|valid_fullname|is_unique[users_model.display_name]',
    'error_msg' => array(
      'is_unique'  => 'The name in %s is already being used by someone.',
    ),
  ),
);

Rest are how we are use normally. Hope these examples are enough.

I haven't tried in v2.1.x but hopefully this will work. Maybe have to do some minor adjustments.



来源:https://stackoverflow.com/questions/15475543/codeigniter-custom-validation-errors-for-each-rule-per-each-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!