CakePHP Creating Validators

PHPz
Release: 2024-09-10 17:26:58
Original
557 people have browsed it

Validator can be created by adding the following two lines in the controller.

use Cake\Validation\Validator;
$validator = new Validator();
Copy after login

Validating Data

Once, we have created validator, we can use the validator object to validate data. The following code explains, how we can validate data for login webpage.

$validator->notEmpty('username', 'We need username.')->add(
   'username', 'validFormat', ['rule' => 'email','message' => 'E-mail must be valid']);

$validator->notEmpty('password', 'We need password.');
$errors = $validator->errors($this->request->data());
Copy after login

Using the $validator object, we have first called the notEmpty() method, which will ensure that the username must not be empty. After that, we have chained the add() method to add one more validation for proper email format.

After that we have added validation for password field with notEmpty() method, which will confirm that password field must not be empty.

Example

Make Changes in the config/routes.php file as shown in the following program.

config/routes.php

<?php
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
$routes->setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder $builder) {
   $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([
      'httpOnly' => true,
   ]));
   $builder->applyMiddleware('csrf');
   //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']);
   $builder->connect('validation',['controller'=>'Valids','action'=>'index']);
   $builder->fallbacks();
});
Copy after login

Create a ValidsController.php file at src/Controller/ValidsController.php. Copy the following code in the controller file.

src/Controller/ValidsController.php

<?php
   namespace App\Controller;
   use App\Controller\AppController;
   use Cake\Validation\Validator;
   class ValidsController extends AppController{
      public function index(){
         $validator = new Validator();
         $validator->notEmpty('username', 'We need username.')->add(
            'username', 'validFormat', ['rule' => 'email','message' => 'E-mail must be valid']);
         $validator->notEmpty('password', 'We need password.');
         $errors = $validator->errors($this->request->getData());
         $this->set('errors',$errors);
      }
   }
?>
Copy after login

Create a directory Valids at src/Template and under that directory create a View file called index.php. Copy the following code in that file.

src/Template/Valids/index.php

<?php
   if($errors) {
      foreach($errors as $error)
      foreach($error as $msg)
      echo '<font color="red">'.$msg.'</font><br>';
   } else {
      echo "No errors.";
   }
   echo $this->Form->create(NULL,array('url'=>'/validation'));
   echo $this->Form->control('username');
   echo $this->Form->control('password');
   echo $this->Form->button('Submit');
   echo $this->Form->end();
?>
Copy after login

Execute the above example by visiting the following URL −

http://localhost/cakephp4/validation

Output

Click on the submit button without entering anything. You will receive the following output.

Click PHP

Http - Client

The http client can be used to make requests like GET, POST, PUT etc.

To work with http client, add the following −

use Cake\Http\Client;
Copy after login

Let us work on example to understand working of HTTP client.

HTTP GET Method

To get the data from give http url, you can do as follows −

$response = $http->get('https://jsonplaceholder.typicode.com/users');
Copy after login

In case, you need to pass some query params, they can be passed as follows −

$response = $http->get('https://jsonplaceholder.typicode.com/users', ["id", 1]);
Copy after login

To get the response, you can do as follows −

For normal text data

$response->getBody();
Copy after login

For Json

$response->getJson();
Copy after login

For Xml

$response->getXml()
Copy after login

Example

Make Changes in the config/routes.php file as shown in the following program.

config/routes.php

<?php
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
$routes->setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder $builder) {
   $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([
      'httpOnly' => true,
   ]));
   $builder->applyMiddleware('csrf');
   //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']);
   $builder->connect('getData',['controller'=>'Requests','action'=>'index']);
   $builder->fallbacks();
});
Copy after login

Create a RequestsController.php file at src/Controller/RequestsController.php. Copy the following code in the controller file.

src/Controller/RequestsController.php

<?php
   namespace App\Controller;
   use App\Controller\AppController;
   use Cake\Http\Client;
   class RequestsController extends AppController{
      public function index(){
         $http = new Client();
         $response = $http->get('https://jsonplaceholder.typicode.com/users');
         $stream = $response->getJson();
         $this->set('response',$stream);
      }
   }
?>
Copy after login

Create a directory Requests at src/Template and under that directory create a View file called index.php. Copy the following code in that file.

src/Template/Requests/index.php

<h3>All Users from url : https://jsonplaceholder.typicode.com/users</h3>
<?php
   if($response) {
      foreach($response as $res => $val) {
         echo '<font color="gray">Name: '.$val["name"].' Email -'.$val["email"].'</font><br>';
      }
   }
?>
Copy after login

Execute the above example by visiting the following URL −

http://localhost/cakephp4/getData
Copy after login

Output

Click on the submit button without entering anything. You will receive the following output.

Users URL

HTTP POST Method

To work with post, you need to call $http client as follows −

$response = $http->post('yoururl', data);
Copy after login

Let us see one example on the same.

Example

Make Changes in the config/routes.php file as shown in the following program.

config/routes.php

<?php
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
$routes->setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder $builder) {
   $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([
      'httpOnly' => true,
   ]));
   $builder->applyMiddleware('csrf');
   //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']);
   $builder->connect('postData',['controller'=>'Requests','action'=>'index']);
   $builder->fallbacks();
});
Copy after login

Create a RequestsController.php file at src/Controller/RequestsController.php. Copy the following code in the controller file. Ignore if already created.

src/Controller/RequestsController.php

<?php
   namespace App\Controller;
   use App\Controller\AppController;
   use Cake\Http\Client;
   class RequestsController extends AppController{
      public function index(){
         $http = new Client();
         $response = $http->post('https://postman-echo.com/post', [
            'name'=> 'ABC',
            'email' => 'xyz@gmail.com'
         ]);
      }
   }
?>
Copy after login

Create a directory Requests at src/Template and under that directory create a View file called index.php. Copy the following code in that file.

src/Template/Requests/index.php

<h3>Testing Post Method</h3>
Copy after login

Execute the above example by visiting the following URL −

http://localhost/cakephp4/postData

Output

Given below is the output of the code −

Post Method

Similarly, you can try for PUT method.

$http = new Client();
$response = $http->put('https://postman-echo.com/post', [
   'name'=> 'ABC',
   'email' => 'xyz@gmail.com'
]);
Copy after login

The above is the detailed content of CakePHP Creating Validators. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template