LoginSignup
2
7

More than 5 years have passed since last update.

cakePHP3で複数フィールドにまたがるカスタムバリデーション

Posted at

cakePHP3で複数フィールドの日付を比較するカスタムバリデーション

カスタムバリデーションに設定している関数の第二引数には入力されたデータがそのまんま入っているのでそれを利用する。

入力された日時データは配列になっているのでFrozenTimeに変換。
あとはChronosで日付の比較が使えるようになるのでそれを使ってバリデーションの正否を返す。

AppTable.php
use Cake\Database\Type;

$validator
            ->add('end_date', 'custom',
            [
                'rule' => function($value, $data){
                        //終了日が開始日より前になっていないかチェック
                        $end = Type::build('date')->marshal($value);
                        $start = Type::build('date')->marshal($data['data']['start_date']);
                        return $end->gt($start);
                 },
                 'message' => '期間が正しくありません'
            ]);

Chronos超便利で感動した

参考

CakePHP3のChronosの機能紹介
Converting array to string for date format in CakePHP 3.x

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