Validating fields as unique in cakephp 3.0
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.
Related videos on Youtube
GatorGuy023
Updated on September 15, 2022Comments
-
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 over 7 yearsThe 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 over 6 yearsHow to show custom message instead of,
Provided value is invalid
for unique fields? -
Rod over 6 yearsI 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 about 6 yearsThanks a lot!!! I was using buildRules(RulesChecker $rules) which was working fine but not giving proper error message
-
pkk about 6 yearsFound an issue not working during edit time. Can you plz help?
-
Marwan Salim almost 5 yearsGood Reference Click Here CakePHP _validateUnique