Validator can be created by adding the following two lines in the controller.
use Cake\Validation\Validator; $validator = new Validator();
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());
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(); });
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); } } ?>
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(); ?>
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.

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;
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');
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]);
To get the response, you can do as follows ?
For normal text data ?
$response->getBody();
For Json ?
$response->getJson();
For Xml ?
$response->getXml()
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(); });
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); } } ?>
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>'; } } ?>
Execute the above example by visiting the following URL ?
http://localhost/cakephp4/getData
Output
Click on the submit button without entering anything. You will receive the following output.

HTTP POST Method
To work with post, you need to call $http client as follows ?
$response = $http->post('yoururl', data);
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(); });
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' ]); } } ?>
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>
Execute the above example by visiting the following URL ?
http://localhost/cakephp4/postData
Output
Given below is the output of the code ?

Similarly, you can try for PUT method.
$http = new Client(); $response = $http->put('https://postman-echo.com/post', [ 'name'=> 'ABC', 'email' => 'xyz@gmail.com' ]);
The above is the detailed content of CakePHP Creating Validators. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

In JavaScript, you need to use a custom function to determine whether two arrays are equal, because there is no built-in method. 1) Basic implementation is to compare lengths and elements, but cannot process objects and arrays. 2) Recursive depth comparison can handle nested structures, but requires special treatment of NaN. 3) Special types such as functions and dates need to be considered, and further optimization and testing are required.

Social security number verification is implemented in PHP through regular expressions and simple logic. 1) Use regular expressions to clean the input and remove non-numeric characters. 2) Check whether the string length is 18 bits. 3) Calculate and verify the check bit to ensure that it matches the last bit of the input.

The methods to correctly handle this pointing in JavaScript closures include: 1. Use arrow functions, 2. Use bind methods, 3. Use variables to save this. These methods ensure that this intrinsic function correctly points to the context of the external function.

Using JavaScript to implement data encryption can use the Crypto-JS library. 1. Install and introduce the Crypto-JS library. 2. Use the AES algorithm for encryption and decryption to ensure that the same key is used. 3. Pay attention to the secure storage and transmission of keys. It is recommended to use CBC mode and environment variables to store keys. 4. Consider using WebWorkers when you need high performance. 5. When processing non-ASCII characters, you need to specify the encoding method.

The steps to deploy a Joomla website on PhpStudy include: 1) Configure PhpStudy, ensure that Apache and MySQL services run and check PHP version compatibility; 2) Download and decompress PhpStudy's website from the official Joomla website, and then complete the installation through the browser according to the installation wizard; 3) Make basic configurations, such as setting the website name and adding content.

In PHP, the constructor is defined by the \_\_construct magic method. 1) Define the \_\_construct method in the class, which will be automatically called when the object is instantiated and is used to initialize the object properties. 2) The constructor can accept any number of parameters and flexibly initialize the object. 3) When defining a constructor in a subclass, you need to call parent::\_\_construct() to ensure that the parent class constructor executes. 4) Through optional parameters and conditions judgment, the constructor can simulate the overload effect. 5) The constructor should be concise and only necessary initialization should be done to avoid complex logic or I/O operations.

The benefits of using dependency injection (DI) in PHP include: 1. Decoupling, making the code more modular; 2. Improve testability and easy to use Mocks or Stubs; 3. Increase flexibility and facilitate reusing of dependencies; 4. Improve reusability, and the classes can be used in different environments. By passing dependencies externally to objects, DI makes the code easier to maintain and extend.

To change the root directory of PhpStudy's website, you can use the following steps: 1. Find the httpd.conf file under the PhpStudy installation directory. 2. Modify the DocumentRoot directive to the new directory path. 3. Save the file and restart the Apache service. Advanced usage allows you to manage multiple root directories by setting up a virtual host. Pay attention to checking the path and permissions to ensure that Apache restarts successfully.
