How to customize form validation errors in codeIgniter

前端 未结 8 2240
刺人心
刺人心 2021-01-05 07:18

Is there a file in codeIgniter in which I could just edit so that I can customize the form validation messages?

<script

8条回答
  •  不思量自难忘°
    2021-01-05 07:51

    You can extend the form_validation class for maximum control by creating application/libraries/MY_form_validation.php to add extra validation rules - I've attached an example below.

    It is bad practice to edit system libraries directly; CI provides better options (overrides/customization thru MY_ classes, libraries, hooks, etc). This gives you the benefit of easily upgrading CI versions & keeps your application portable / custom code isolated from the core framework.

    CI->form_validation->set_message('valid_url', 'The %s must be a valid URL.');
            return FALSE;
        }
    
        /**
         * MY_Form_validation::alpha_extra()
         * @abstract Alpha-numeric with periods, underscores, spaces and dashes
         */
        function alpha_extra($str) {
            $this->CI->form_validation->set_message('alpha_extra', 'The %s may only contain alpha-numeric characters, spaces, periods, underscores & dashes.');
            return ( ! preg_match("/^([\.\s-a-z0-9_-])+$/i", $str)) ? FALSE : TRUE;
        }
    
        /**
         * MY_Form_validation::numeric_comma()
         * @abstract Numeric and commas characters
         */
        function numeric_comma($str) {
            $this->CI->form_validation->set_message('numeric_comma', 'The %s may only contain numeric & comma characters.');
            return ( ! preg_match("/^(\d+,)*\d+$/", $str)) ? FALSE : TRUE;
        }
    
        /**
         * MY_Form_validation::matches_pattern()
         * @abstract Ensures a string matches a basic pattern
         */
        function matches_pattern($str, $pattern) {
            if (preg_match('/^' . $pattern . '$/', $str)) return TRUE;
            $this->CI->form_validation->set_message('matches_pattern', 'The %s field does not match the required pattern.');
            return FALSE;
        }   
    
    }
    
    /* End of file MY_form_validation.php */
    /* Location: ./{APPLICATION}/libraries/MY_form_validation.php */
    

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题