LoginSignup
1
1

More than 1 year has passed since last update.

CodeIgniter4 の $this->validate() でラベル付きのエラーメッセージを使用する

Last updated at Posted at 2022-04-15

公式ドキュメントに記法が示されていなかったので。

確認環境

  • CodeIgniter4 v4.1.9
  • PHP 8.1.4

対応方法

Controller クラスの validate() メソッドでラベル付きのエラーメッセージを使用する場合は以下。

UserController
public function create()
{
    $input = $this->validate([
-       'name'     => 'required|max_length[100]',
-       'email'    => 'required|valid_email|is_unique[users.email]',
-       'password' => 'required|min_length[8]'
+       'name'     => ['label' => 'ユーザー名', 'rules' => 'required|max_length[100]'],
+       'email'    => ['label' => 'メールアドレス', 'rules' => 'required|valid_email|is_unique[users.email]'],
+       'password' => ['label' => 'パスワード', 'rules' => 'required|min_length[8]']
    ]);

    if (!$input) {
        return view('users/create', [
            'validation' => $this->validator
        ]);
    }
    // ...
}

変更前
image.png

変更後
image.png

補足

公式ドキュメントより

The validate() method is a method in the Controller. It uses the Validation class inside. See Validating data in Controllers.

結局、Validation クラス の setRules() メソッドが呼び出されているだけである。

/vendor/codeigniter4/framework/system/Controller.php
protected function validate($rules, array $messages = []): bool
{
    $this->validator = Services::validation();

    // If you replace the $rules array with the name of the group
    if (is_string($rules)) {
        $validation = config('Validation');

        // If the rule wasn't found in the \Config\Validation, we
        // should throw an exception so the developer can find it.
        if (! isset($validation->{$rules})) {
            throw ValidationException::forRuleNotFound($rules);
        }

        // If no error message is defined, use the error message in the Config\Validation file
        if (! $messages) {
            $errorName = $rules . '_errors';
            $messages  = $validation->{$errorName} ?? [];
        }

        $rules = $validation->{$rules};
    }

    return $this->validator->withRequest($this->request)->setRules($rules, $messages)->run();
}
1
1
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
1
1