public function buildRules(RulesChecker $rules)
    {
        // check max instances limit
        $rules->addCreate(function ($instance, $options) {
            $info = (array)$instance->info();
            if (isset($info['maxInstances']) && $info['maxInstances'] > 0) {
                if (!$instance->get('eav_attribute')) {
                    return false;
                }

                $count = $this
                    ->find()
                    ->select(['FieldInstances.id', 'FieldInstances.handler', 'EavAttribute.id', 'EavAttribute.table_alias'])
                    ->contain(['EavAttribute'])
                    ->where([
                        'EavAttribute.table_alias' => $instance->get('eav_attribute')->get('table_alias'),
                        'FieldInstances.handler' => $instance->get('handler'),
                    ])
                    ->count();

                return ($count <= (intval($info['maxInstances']) - 1));
            }

            return true;
        }, 'maxInstances', [
            'errorField' => 'label',
            'message' => __d('field', 'No more instances of this field can be attached, limit reached.'),
        ]);

        return $rules;
    }