19
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CakePHP 3.xでカスタムバリデーション追加(例:画像幅チェック)

Last updated at Posted at 2015-05-19

カスタムバリデーションクラス作成

src/ModelにValidationフォルダを作成し、その中にCustomValidation.phpを作ります。

src/Model/Validation/CustomValidation.php
<?php
namespace App\Model\Validation;

use Cake\Validation\Validation;

class CustomValidation extends Validation
{
    public static function imageSize($check, $width, $height)
    {
        $size = getimagesize($check['tmp_name']);
        return ($size[0] == $width) && ($size[1] == $height);
    }
}
  • メソッドはpublic staticにします

$validatorに定義

先ほどのメソッドを使うTableを編集します。

   public function validationDefault(Validator $validator)
    {
        $validator->provider('custom', 'App\Model\Validation\CustomValidation');
        $validator
            ->allowEmpty('thumbnail', 'update')
            ->add('thumbnail', [
                'uploadedFile' => [
                    'rule' => ['uploadedFile', ['types' => ['image/jpeg'], 'maxSize' => '16MB']],
                    'last' => true,
                    'message' => 'JPEG file is required (max size is 16MB).'
                ],
                'imageSize' => [
                    'rule' => ['imageSize', 100, 200],
                    'provider' => 'custom',
                    'message' => '100x200 JPEG file is required.']
            ]);
        return $validator;
    }
  • allowEmpty('thumbnail', 'update')で、新規追加のみ必須項目としています
  • $validator->providerでカスタムクラスを指定します
  • 上記サンプルでは先にファイルサイズ及びMime-Typeのチェックをし、image/jpegでなければ'last'=>trueによりチェックが止められます
  • カスタムメソッドを使う際、忘れず'provider' => 'custom'の指定を入れること
19
16
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
19
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?