Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Model Validation Using cakephp 3.x with Example

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.81k
    Comment on it

    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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: