【问题标题】:how to use validationDefault( ) in cakephp 4如何在 cakephp 4 中使用validationDefault()
【发布时间】:2020-08-20 20:44:03
【问题描述】:

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

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

  2. 密码需要具备以下规则: 一世。至少 1 个号码 ii.至少 1 个大写字符 iii.至少 1 个小写字符 iv.至少 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;
    }


【问题讨论】:

    标签: cakephp cakephp-4.x


    【解决方案1】:

    adding validation rules 上的文档不包含开箱即用功能的列表,而是引用了API documentation。您可能想要的用户名是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 ...'
    ])
    

    【讨论】:

      猜你喜欢
      • 2018-11-19
      • 1970-01-01
      • 2021-11-22
      • 2022-01-22
      • 2021-04-02
      • 1970-01-01
      • 2013-09-24
      • 2021-07-25
      • 2011-06-14
      相关资源
      最近更新 更多