CakePHP uses a two-layered approach to validation:
1. Validation
It determines basic validity. It ensures that the data types, size, and format of data are correct. When we call newEntity() or patchEntity() methods, validations are triggered. For example, checking if an email address is valid.
Some of Built-in Validation methods:
$validator = new Validator();
a. $validator->requirePresence(
b. $validator->notEmpty(
c. $validator->lengthBetween(
d. $validator->add(
2. Application Rules
It checks the stateful properties of your entities. It commonly deals with the database to check data is correct or not. By using application rules, you can work with the data of an entity that is stored in the database. So that you will have full permission to access the current state of an object.
For example, if you want to check an email address is unique or you can not withdraw money more than your account balance.
$rules = RulesChecker;
a. $rules->isUnique(
b. $rules->existsIn(
c. $rules->validCount(
NOTE: When we directly set properties of our entities, validation will not get triggered because validation methods only work for newEntity() and patchEntity() methods.
For example:
$user->email = 'email invalid!!'; $usersTable->save($user);
In the above example , the entity will be saved without checking email is valid or not. In this case, incorrect data will be saved into the database.
Now, we will use application rules method to determine the validity of data. Application rules will be checked when save() or delete() methods are called. We will define this rule as below:
public function buildRules(RulesChecker $rules) { $rules->add($rules->isUnique(['email'])); return $rules; }
Now when we call the save() function to save the above entity, the save() function returns false and will not be allowed to save the data into database.