Validating fields as unique in cakephp 3.0

13,195

Solution 1

You want to use the rule validateUnique. For example, to check an email address is unique on an UsersTable:-

public function validationDefault(Validator $validator)
{
    $validator->add(
        'email', 
        ['unique' => [
            'rule' => 'validateUnique', 
            'provider' => 'table', 
            'message' => 'Not unique']
        ]
    );

    return $validator;
}

Details can be found in the API docs.

Solution 2

you have to use the rules from cake's ORM on your table...

add this at the top of your UsersTable after your namespace

use Cake\ORM\Rule\IsUnique;

Then prepare your rule to apply to your field by placing it in a public function

public function buildRules(RulesChecker $rules){
        $rules->add($rules->isUnique(['email']));
        return $rules;
    }

Consult the cakephp documentation for more information about RULES

Solution 3

Validation providers can be objects, or class names. If a class name is used the methods must be static. To use a provider other than ‘default’, be sure to set the provider key in your rule:

// Use a rule from the table provider
$validator->add('title', 'unique', [
    'rule' => 'uniqueTitle',
    'provider' => 'table'
]);

For more details, look at the Adding Validation Providers section in the CakePHP3 reference book.

Share:
13,195

Related videos on Youtube

GatorGuy023
Author by

GatorGuy023

Updated on September 15, 2022

Comments

  • GatorGuy023
    GatorGuy023 over 1 year

    How do you validate a field is unique in cakephp 3.0? There doesn't appear to be a validation function listed in the API.

  • Stephan
    Stephan over 7 years
    The link provided by ADMad is the an excellent and possibly the best solution. In your Table's buildRules function, add a rule: $rules->add($rules->isUnique(['UNIQUE_COLUMN']));
  • Anuj TBE
    Anuj TBE over 6 years
    How to show custom message instead of, Provided value is invalid for unique fields?
  • Rod
    Rod over 6 years
    I correct myself, isUnique has only 2 parameters, public function isUnique(array $fields, $message = null){ so your code will be like: $rules->add($rules->isUnique(['email'],'Your message here!'));
  • pkk
    pkk about 6 years
    Thanks a lot!!! I was using buildRules(RulesChecker $rules) which was working fine but not giving proper error message
  • pkk
    pkk about 6 years
    Found an issue not working during edit time. Can you plz help?
  • Marwan Salim
    Marwan Salim almost 5 years