Validating fields as unique in cakephp 3.0

GatorGuy023 picture GatorGuy023 · Jul 11, 2015 · Viewed 12k times · Source

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.

Answer

drmonkeyninja picture drmonkeyninja · Jul 11, 2015

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.