Sitemap
Online Web Tutor

Online Web Tutor

Online Web Tutor basically gives you the platform to learn Web Development Programming Skills . It makes you from state of Novice to a Standard Programmer .

Validating a form is common to every application. Inside this article we will see CakePHP 4 Custom Validation rule for form elements. This will be step by step guide with example.

We will set an application, inside that we will create controller, model and a view file.

Let’s get started.

CakePHP 4 Application Setup

To Install CakePHP 4 in system, we need to first setup composer. If your system already contains the installation of Composer. Type the command

Command — $ composer to verify the composer installation. If you need more help please click into this link CakePHP 4 Basics.

Let’s assume your system already contains the composer. We are going to install CakePHP 4 application setup.

Composer command to create CakePHP 4 project –

$ composer create-project –prefer-dist cakephp/app:~4.0 mycakephp

Get Online Web Tutor’s stories in your inbox

Join Medium for free to get updates from this writer.

Above command will creates a project with the name called mycakephp. Successfully, we have done the installation.

$validator = new Validator()

Adding Validation Rules for validator

These are system defined.

$validator
->requirePresence(“email”)
->notEmpty(“email”, “Email field value is needed”)
->add(“email”, [
“valid_email” => [
“rule” => [“email”],
“message” => “Email Address is not valid”,
],
“min_length” => [
“rule” => [“minLength”, 10],
“message” => “Invalid min length”,
],
“max_length” => [
“rule” => [“maxLength”, 25],
“message” => “Invalid max length”,
],
])
->requirePresence(“phone_no”)
->numeric(“phone_no”);

Adding Custom Rule for validator

This is custom added rule for input field name

$validator
->add(“name”, “custom”, [
“rule” => function($value, $context){
if(empty($value)){
return “Name field should not be empty”;
}

if(strlen($value) < 10){
return “Name field should not have min length less than 10”;
}

if(strlen($value) > 20){
return “Name field should not exceed from 20 chars”;
}
return true;
}
]);

For complete information, click this link.

--

--

Online Web Tutor
Online Web Tutor

Written by Online Web Tutor

0 followers

Online Web Tutor basically gives you the platform to learn Web Development Programming Skills . It makes you from state of Novice to a Standard Programmer .