2
7

More than 5 years have passed since last update.

codeigniterで独自のバリデーションルールを作成する。4バイト(絵文字)文字を禁止にする。

Posted at

APIにエラーを送る時の方法

通常のcodeigniterでのバリデーションルールと独自に作成したバリデーションルールの設定方法。

controller
function get_bpass() {
  $form = $this->input->post();


  //codeigniterのバリデーションルールを走らせる。
  $this->form_validation->set_rules($this->Backup_model->rules[__FUNCTION__]);
  if (!$this->form_validation->run()) {

            $this->form_validation->set_error_delimiters('', '');
            $error = [
                'error' => trim(validation_errors()),
            ];
            $this->json_library->_echo(201, $form, $error, validation_errors());
        }

   //独自バリデーション(_is_valid_text)を走らせる。
        $this->form_validation->set_rules($this->Backup_model->rules['search_is_valid_string']);
        if (!$this->form_validation->run()) {
            $this->form_validation->set_error_delimiters('', '');
            $error = [
                'error' => trim(validation_errors()),
            ];
            $this->json_library->_echo(201, $form, $error, validation_errors());
        }


//独自のバリデーションルール。
//ここでは4バイト文字(絵文字とか)を弾く処理
//アンダーバー(_)を先頭に付けないとURLが生成されちゃうので注意。付けること。
public function _is_valid_text($text) {
        if (preg_match('/[\xF0-\xF7][\x80-\xBF][\x80-\xBF][\x80-\xBF]/', $text)) {

       //第一引数に_付けるのを忘れずに。
            $this->form_validation->set_message('_is_valid_text', '使用できない文字が含まれています。');
            return false;
        }
        return true;
    }

//  以下処理省略

}
model
    public function __construct() {
        parent::__construct();


        $this->rules['is_valid_string'] = [
            array(
                'field' => 'B_PASS',
                'label'=>'名前',
                  //ここでcallbackする事で独自のバリデーションルールを呼び出せる。
                'rules' => 'trim|callback__is_valid_text',
            ),

        ];
        $this->rules['get_bpass'] = [
            [
                'field' => 'UUID',
                'rules' => 'required',
            ],
            [
                'field' => 'B_PASS',
                'label' => 'パスワード',
                'rules' => 'required|min_length[6]|max_length[16]|alpha_numeric|trim',
            ],
        ];
    }

2
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
7