LoginSignup
3
3

More than 3 years have passed since last update.

[CodeIgniter]バリデーションで独自バリデーションに引数を2つ以上渡す方法

Posted at

はじめに

実務でCodeIgniterを使用する機会があり、バリデーションの処理で独自バリデーションに引数を2つ以上渡すのに苦戦し、その時に解決した方法をまとめました。

解決方法

手順1 独自バリデーションに渡したい値をJSON形式で変数に格納

// 今回は送信されたデータ4つを渡したい
$json_param = [
    'user_id"   => $this->input->post('user_id'),
    'user_name' => $this->input->post('user_name'),
    'password'  => $this->input->post('password'),
    'email'     => $this->input->post('email')
];

手順2 user_name_checkルールを作成し、独自バリデーションcallback_user_name_checkを作成する

// callback_user_name_checkの引数に1で作成した$json_paramを指定
$this->form_validation->set_rules('user_name', 'ユーザ名', 'callback_user_name_check['.json_decode($json_param).']');

手順3 独自バリデーション先でパラメータを受け取る

public function user_name_check($user_name, $json_data) {
    // JSON⇒オブジェクト型に変換
    $data = json_decode($json_data);

    // キーにアクセスし、変数に格納
    $user_id  = $data->user_id;
    $password = $data->user_name;
    $email    = $data->email;
}

user_name_checkメソッドの第1引数を$user_nameに指定しているのはCodeIgniterの仕様上で、第1引数は必ず検証ルールで作成したフィールドのデータが渡されるからです。

参考

CodeIgniter公式

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