[CodeIngiter3]バリデーションまとめ

■基本

application/controllers/Sample.php

// ライブラリ呼び出し
$this->load->library('form_validation');

// ルールを設定
$this->form_validation->set_rules('[FORM変数名1]', '[タイトル1]', '[ルール1]');
$this->form_validation->set_rules('[FORM変数名2]', '[タイトル2]', '[ルール2]');

// 検証結果
if ($this->form_validation->run() == FALSE) {
	// NG時の処理
	$data['error'] = $this->form_validation->error_array();
	// Twigにエラーを渡す
	$this->twig->display('input.twig', $data);
} else {
	// OK時の処理
	$this->twig->display('confirm.twig', $data);
}

■ルール

※パイプ(|)で連結して複数指定できる。

required
必須
matches
他のフォーム値と一致
matches[form_elem]
regex_match
正規表現での一致
regex_match[/regex/]
differs
他のフォーム値と異なる
differs[form_item]
is_unique
テーブルのフィールドに存在しないか
is_unique[table.field]
min_length
最小文字数
min_length[3]
max_length
最大文字数
max_length[12]
exact_length
文字数一致
exact_length[8]
greater_than
数字で指定数以上
greater_than[8]
greater_than_equal_to
数字で指定数超え
greater_than_equal_to[8]
less_than
数字で指定数以下
less_than[8]
less_than_equal_to
数字で指定数未満
less_than_equal_to[8]
in_list
リストに存在する
in_list[red,blue,green]
alpha
半角アルファベットのみ
alpha_numeric
半角アルファベットと半角数字のみ
numeric
半角数字のみ
integer
半角整数のみ
decimal
小数点を含む半角数字のみ
is_natural
半角自然数(0と正の整数)のみ
valid_url
URLとして正しい
valid_email
emailとして正しい
valid_ip
IPアドレスとして正しい(ipv4またはipv6)

■ユーザ定義

※『callback_』を付け加えることによりコントローラー内のメソッドに渡すことができる。

$this->form_validation->set_rules('test', 'テスト', 'required|callback_is_user');

/**
 * テストバリデーションメソッド
 */
public function is_user($str) {
	if ($str == 'admin') {
		$this->form_validation->set_message('is_user', '%s は存在します。');
		return FALSE;
	} else {
		return TRUE;
	}
}

※[]内にパラメータを設定すると第2引数として渡すことができる。

$this->form_validation->set_rules('test', 'テスト', 'required|callback_is_user[1]');
/**
 * テストバリデーションメソッド
 */
public function is_user($str, $ex = null) {
	if (!is_null($ex) && $str == 'admin') {
		$this->form_validation->set_message('is_user', '%s は存在します。');
		return FALSE;
	} else {
		return TRUE;
	}
}

■ライブラリ化

application/libraries/MY_Form_validation.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class MY_Form_validation extends CI_Form_validation {

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

	/**
	 * アカウント重複チェック
	 */
	public function is_account($account, $exid = null) {
		$this->CI->load->model('model_user');
		$result = $this->CI->model_user->is_exists('account', $account, $exid);
		if ($result) {
			// 存在
			$this->set_message('is_account', '%s はすでに登録されています。');
			return FALSE;
		} else {
			// OK
			return TRUE;
		}
	}

	/**
	 * 郵便番号チェック
	 */
	public function valid_postalcode($postalcode) {
		if (!preg_match("/^[0-9]{3}[\-]*?[0-9]{4}$/", $postalcode)) {
			// NG
			$this->set_message('valid_postalcode', '%s を正しく入力してください。');
			return FALSE;
		} else {
			// OK
			return TRUE;
		}
	}

	/**
	 * 電話番号チェック
	 */
	public function valid_tel($tel) {
		if (!preg_match("/^[0-9][\-0-9]+?[0-9]$/", $tel)) {
			// NG
			$this->set_message('valid_tel', '%s を正しく入力してください。');
			return FALSE;
		} else {
			// OK
			return TRUE;
		}
	}
}

※コアクラスを継承するときのクラス名はMY_+コアクラス名としなければならない。

application/config/config.php

$config['subclass_prefix'] = 'MY_';

コントローラーからの呼び出し

$this->load->library('form_validation');
$this->load->library('my_form_validation');
$this->form_validation->set_rules('account', 'アカウント', 'required|is_account[1]');