0

How can i change this code based on this question?

  1. Username can only accept character and numbers (no special characters)

  2. Password needs to have the following rules: i. At least 1 number ii. At least 1 uppercase character iii. At least 1 lowercase character iv. At least 1 special character


 /**
     * 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;
    }


1 Answers1

2

The documentation on 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, you replace ->scalar('username') with ->alphaNumeric('username').

There's no built-in validation that matches what you want from passwords, so you'll have to write a custom validation rule. You'll see there are various options here; the easiest is probably to use a closure. Instead of ->scalar('password') you'd use

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