As we all know that validation plays an important role in any technology. In cakephp 3.x we will implement either model validation or javascript validation. Steps to implement model validation is as follow.
Step 1: Fisrt we have to set the validation rule in our model .The path to reach model in cakephp 3.x is
//"src/Model/Table/"
Example of model code
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class UsersTable extends Table
{
public function initialize(array $config)
{
$this->addBehavior('Timestamp');
}
public function validationDefault(Validator $validator)
{
return $validator
->notEmpty('username', 'A username is required')
->notEmpty('password', 'A password is required')
->notEmpty('role', 'A role is required')
->add('role', 'inList', [
'rule' => ['inList', ['admin', 'user']],
'message' => 'Please enter a valid role'
])
->requirePresence('email')
->add('email', 'validFormat', [
'rule' => 'email',
'message' => 'E-mail must be valid'
]);
}
}
Here in the example we can see that we are using validator class and the set the rules in validationDefault function. We can also define all validation rule to the fields after creating the validation class as follow:
//"src/Model/Table/"
use Cake\Validation\Validator;
$validator = new Validator();
By this way we are able to implement cakephp 3.x model validation.
0 Comment(s)