如何在 cakephp 4 中使用 validationDefault()

how to use validationDefault( ) in cakephp 4

我如何根据这个问题更改此代码?

  1. 用户名只能接受字符和数字(无特殊字符)

  2. 密码需要符合以下规则: 一世。至少 1 个号码 二.至少 1 个大写字符 三.至少 1 个小写字符 四.至少 1 个特殊字符


 /**
     * Default validation rules.
     *
     * @param \Cake\Validation\Validator $validator Validator instance.
     * @return \Cake\Validation\Validator
     */
    public function validationDefault(Validator $validator): Validator
    {
        $validator
            ->nonNegativeInteger('id')
            ->allowEmptyString('id', null, 'create');

        $validator
            ->scalar('username')
            ->maxLength('username', 12)
            ->requirePresence('username', 'create')
            ->notEmptyString('username');

        $validator
            ->scalar('password')
            ->maxLength('password', 255)
            ->requirePresence('password', 'create')
            ->notEmptyString('password');

        $validator
            ->email('email')
            ->requirePresence('email', 'create')
            ->notEmptyString('email');

        $validator
            ->scalar('role')
            ->maxLength('role', 20)
            ->allowEmptyString('role');

        return $validator;
    }

    /**
     * Returns a rules checker object that will be used for validating
     * application integrity.
     *
     * @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
     * @return \Cake\ORM\RulesChecker
     */
    public function buildRules(RulesChecker $rules): RulesChecker
    {
        $rules->add($rules->isUnique(['username']));
        $rules->add($rules->isUnique(['email']));

        return $rules;
    }


关于 adding validation rules doesn't include a list of the out-of-the-box functions, but rather references the API documentation. What you presumably want for username is alphaNumeric 的文档,您将 ->scalar('username') 替换为 ->alphaNumeric('username')

没有与您想要的密码匹配的内置验证,因此您必须编写 custom validation rule。您会看到这里有多种选择;最简单的可能是使用闭包。而不是 ->scalar('password') 你会使用

->add('password', 'custom', [
    'rule' => function ($value, $context) {
        // Custom logic that returns true/false; the password will be in the $value
    },
    'message' => 'Password must contain ...'
])