CakePHP 3 Data Validation

Validating your data before saving it is an important process. If you have a non-validated form that gathers data about users, products, topics etc, you might find strange data; invalid phone numbers, prices, birthdates etc. Not only invalid data but also having many errors when your system tries to handle unexpected data. Black-hat hackers will feel happy when your site accepts any request they send without any filtration or validation.

In this tutorial, you will learn how CakePHP can powerfully validate data in models, controllers, and views. The main validation in CakePHP is done in models. Simply you can make aninstantiation of Cake’s validator in models. Then, you can add the validations sets to any fields of this model. The Validator object will validate your data before it is saved.

(Also read: Simple CRUD Operation in CakePHP 3)

Create anew database and create table clients to save registered clients’ data.


--
-- Table structure for table `clients`
--

CREATE TABLE `clients` (
  `id` int(14) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `username` varchar(50) NOT NULL,
  `password` varchar(50) NOT NULL,
  `email` varchar(50) NOT NULL,
  `phone` varchar(25) NOT NULL,
  `zipcode` varchar(20) NOT NULL,
  `birthdate` date NOT NULL,
  `fb_account_url` varchar(100) NOT NULL,
  `credit_card` varchar(100) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
   PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

In /Model/Table/ path, we will create ClientsTable.php file. Write the ClientsTable class code.

namespace App\Model\Table;
use Cake\ORM\Table;

<?php
classClientsTable extends Table {
	
	public function initialize(array $config){
		$this->addBehavior("Timestamp");
			
	}
}

?>

Inside themodelfile, we will use Validator class .In ClientsTable class we will make new function validationDefault()  where we can use default validation rules.

<?php

namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class ClientsTable extends Table {
	
	public function initialize(array $config){
		$this->addBehavior("Timestamp");
			
	}
	public function validationDefault(Validator $validator){
		 $validator->requirePresence('name','You must enter your name')
					 ->add('name', [
			'length' => [
			'rule' => ['minLength', 6],
			'message' => 'Name need to be at least 6 characters long',
			]
			])
					->notEmpty('name','Please, enter your name !')
					->notEmpty('password','Please, enter your password !')
					->add('password', [
					'compare' => [
						'rule' => ['compareWith', 'password2'],
						'message'=>"Password mismatch password confirm !"
						]
					])
					->notEmpty('email','Please, enter your email  !')
					->add('email', [
					'email' => [
						'rule' => ['email'],
						'message'=>" Please, enter a valid email!"
						]
					])						
					->numeric('phone','Please, enter valid phone number !')		
					->date('birthdate','Please, enter valid bith date !')		
					->url('fb_account','Please, enter valid facbook account url  !')
					->allowEmpty('fb_account')		
					->creditCard('credit_card','Please, enter a valid credit card  !')
					->allowEmpty('credit_card')		;	
					return $validator;																		
	}
	
	
	
	
}

?>

In the last code you notice a group of rules:

requirePresence() method means that the field presence is required in any array or request. We used two parameters; the first parameter is the field name, the second parameter is the validation message that appears to the client.

add() method is used to add new validator rules. We used it to add ‘minLength’  rule to the ‘name’ field. This rule takes numeric value to determine the minimum number of characters available in an input.

notEmpty() method means that the value of the filed not allowed to be empty .So, The values '', null and [] (empty array) will cause errors .

note: the difference between requirePresence()method and notEmpty() method  is : requirePresence()  needs the validated field to be exist in the request array. So, if you omit the input field with requirePresence()  from the form, it will make a validation error .

notEmpty()  and allowEmpty() only for an input field  won’t cause errors if the input field was deleted from the form.  notEmpty()  and allowEmpty() only  decide whether it is allowed to left the field input empty or it cannot be empty.

To understand that practically, try to erase the ‘name’ input from ‘add.ctp’ form and register thenewclient. You will get an error.
Try to erase the ‘email’ field from ‘add.ctp’ form then register anewclient, it will not make errors.

  • compare rule is used to compare two fields or compare a field with aspecific value .It was added to ‘password’ field to compare it with ‘password2’ who demonstrates password confirm.
  • email  rule checks the input value if it represents a valid email.
  • numeric rule checks the input value if it is numeric or not.
  • daterule checks the input value if it is a valid date or not.
  • urlrule checks the input value if it is a valid URL or not.
  • creditCardrule checks the input value if it is a valid credit card code or not.

Validation in Controllers:

Create ClientsContoller.php in /Controller/ path and write ClientsControllerclass .

<?php
namespace App\Controller;

use App\Controller\AppController;

class ClientsController extends AppController{

    public function initialize()
    {
        parent::initialize();
		$this->loadComponent('Flash'); // Include the FlashComponent
    }
	
	public function index()
	{
		$this->set('clients',$this->Clients->find('all'));		
	}
	public function view($id)
	{
		$client = $this->Clients->get($id);
		$this->set('client',$client);
		
	}
	public function add()
	{
		$client = $this->Clients->newEntity();
		if($this->request->is('post')) {
			$this->Clients->patchEntity($client,$this->request->data);
			if($this->Clients->save($client)){
            $this->Flash->success(__('Your account has been registered .'));
            return $this->redirect(['action' => 'index']);
			}
			$this->Flash->error(__('Unable to register your account.'));
		}
		$this->set('client',$client);
	}
	public function edit($id)
	{
		$client = $this->Clients->get($id);
		if ($this->request->is(['post', 'put'])) {
			$this->Clients->patchEntity($client, $this->request->data);
			if ($this->Clients->save($client)) {
				$this->Flash->success(__('Your profile data has been updated.'));
				return $this->redirect(['action' => 'index']);
			}
			$this->Flash->error(__('Unable to update your profile.'));
		}
	
		$this->set('client', $client);		
		
	}
	public function delete($id)
	{
		$this->request->allowMethod(['post', 'delete']);
	
		$client = $this->Clients->get($id);
		if ($this->Clients->delete($client)) {
			$this->Flash->success(__('The client with id: {0} has been deleted.', h($id)));
			return $this->redirect(['action' => 'index']);
		}		
		
	}	
}


?>

get() method is used to assure a valid client by its id.

is('post') in the request object checks request type. If there is no post requet, add() function only display add.ctp view.

In add() function ,You can check whether the new entity was saved so you redirect the client with asuccessful message or it wasn’t saved so you use flash object to view failure message.

allowMethod() method in delete() function only allows you to delete clients by POST request and it will throw an exception if you use GET request.

At last, to complete client’s app, Create the view template files.

createadd.ctp

<h1>Register new client </h1> 
<?php

    echo $this->Form->create($client);
    echo $this->Form->input('name');
    echo $this->Form->input('username');
    echo $this->Form->input('password');		
    echo $this->Form->input('password2',array('label'=>"confirm password",'type'=>'password'));	
    echo $this->Form->input('email');
    echo $this->Form->input('phone');	
    echo $this->Form->input('zipcode');	
    echo $this->Form->input('birthdate');	
    echo $this->Form->input('fb_account');	
    echo $this->Form->input('credit_card');			
		
    echo $this->Form->button(__('Register'));
    echo $this->Form->end();
?>

Create view.ctp

<h1><?= h($client->name) ?></h1>
<p>Client username<?= h($client->username) ?></p>

<p>Email :<?= h($client->email) ?></p>
<p>Phone :<?= h($client->phone) ?></p>
<p>Birth date :<?= h($client->birthdate) ?></p>
<p>Facebook account :<?= h($client->fb_account) ?></p>

<p><small>Created: <?= $client->created->format(DATE_RFC850) ?></small></p>

Create edit.ctp

<h1>Edit client data </h1>
<?php

echo $this->Form->create($client);
echo $this->Form->input('name');
echo $this->Form->input('username');
echo $this->Form->input('password');		
echo $this->Form->input('password2',array('label'=>"confirm password"));	
echo $this->Form->input('email');
echo $this->Form->input('phone');	
echo $this->Form->input('zipcode');	
echo $this->Form->input('birthdate');	
echo $this->Form->input('fb_account');	
echo $this->Form->input('credit_card');			
		
echo $this->Form->button(__('Save'));
echo $this->Form->end();
?>

Create index.ctp

<h1>All clients</h1>
<p><?= $this->Html->link('Add Client', ['action' => 'add']) ?></p>
<table>
<tr>
<th>Id</th>
<th>username</th>
<th>Created</th>
<th>Actions</th>
</tr>


<?phpforeach ($clients as $client): ?>
<tr>
<td><?= $client->id ?></td>
<td>
<?= $this->Html->link($client->username, ['action' => 'view', $client->id]) ?>
</td>
<td>
<?= $client->created->format(DATE_RFC850) ?>
</td>
<td>
<?= $this->Form->postLink(
                'Delete',
                ['action' => 'delete', $client->id],
                ['confirm' => __('Are you sure you want to delete client with id # {0}?',$client->id)])
            ?>
<?= $this->Html->link('Edit', ['action' => 'edit', $client->id]) ?>
</td>
</tr>
<?phpendforeach; ?>

</table>

In index view, when you try to delete a client you will get a javascript message Are you sure you want to delete client with id?

At the end of this article, you can validate any model data using CakePHP Validator object .You knew simple Controller’s validation.

If you have any query regarding CakePHP Validation, feel free to write in comment section.

Share this Article on Social Media

All of my Scripts are ready to customized as per your requirement. Feel free to contact for script customization.

Contact me at discussdesk@gmail.com

"Note : It will be charged as per your customization requirement :)"

Get Updates, Scripts & Other Tutorials to Directly to your Email

Over 20000+ Happy Readers already subscribed. (We don't send spam email). Every email subscriber can get our latest updates and download our 100+ scripts.

Comments