CakePHP Validation

Validation means a set of rules which we have defined in form for cross verify with the user inputs. If the user has not provided correct input data according to the rules which we have set for every field in the form, it will show an error, or it will not submit any user data to the database. 

Here we have created a validator object to assign the Validator class.

 use Cake\Validation\Validator; // Validation is a package of Cake in which we have called //validator 
 $validator = new Validator(); // 

Now we have to define all the parameters in validator object to validate the data, when the user doesn’t provide a value in the form. Here we have define the validator object in the form’s fields:

 >?php
 namespace App\Model\Table;
 use Cake\Validation\Validator;
 use Cake\ORM\Table;
 class RegistersTable extends Table
 {
  public function initialize(array $config)
  { //$this->addBehavior('Timestamp'); // You can pass here addition things like as date
  }
 }
 ?> 

By the use of a $validator object, it will call the notEmpty() method that contains the fields name and the message which you want to show when the user didn’t fill any fields. If you’re going to add more validation functionality in your fields, then you can use add() method in validator like.

 $validator
  ->requirePresence('email')
  ->add('email', 'validFormat', [
    'rule' => 'email',
    'message' => 'E-mail must be valid'
  ])
  ->requirePresence('name')
  ->notEmpty('name', 'We need your name.')
  ->requirePresence('comment')
  ->notEmpty('message', 'You need to give feedback.');
 $errors = $validator->errors($this->request->getData());
 if (empty($errors)) {
  // Send an email.
 } 

Example to show the validation in the form

Create a ValidatorsController.php file at src/Controller/ValidatorsController.php. Now write the following code in your controller file.

 $validator
  ->requirePresence('email')
  ->add('email', 'validFormat', [
    'rule' => 'email',
    'message' => 'E-mail must be valid'
  ])
  ->requirePresence('name')
  ->notEmpty('name', 'We need your name.')
  ->requirePresence('comment')
  ->notEmpty('message', 'You need to give feedback.');
 $errors = $validator->errors($this->request->getData());
 if (empty($errors)) {
  // Send an email.
 } 

Create a folder Validators at src/Template, and that folder, creates an index.ctp file. Now write the following code in that file.

src/Template/Validators/index.ctp

 <?php
 if($errors){
 foreach($errors as $error)
 foreach($error as $msg)
 echo '<font color = "red">'.$msg .'</font>l';
 }
 echo $this->Form->create("logins",array('url'=>'/validators'));
 echo $this->Form->input('name');
 echo $this->Form->input('email');
 echo $this->Form->input('password');
 echo $this->Form->button('Submit');
 echo $this->Form->end();
 ?> 

Now run the given code by typing in localhost like: localhost/CakePHP3.8/validators

Output:

Click on the submit button without typing in the form. You will receive the following output.

Or if any field has left then it will also show the message.

CakePHP Validation

Use of Requiring Field Presence in validation

The requiring fields method requires that all the fields should be present for validating in an array. If the fields were not present, then it will show an error. The requirePresence() method has 4 modes:

  • True The fields should always be present.
  • False The fields should not be present.
  • Create The fields should be required when validating a create operation.
  • Update The fields should be required when validating an update operation.   
$validator->requirePresence(['emp_id’, ‘title’], ‘create’);

The above syntax define that validator function will validate your data at performing the create operation in form.

 $validator->requirePresence([
  'emp_id' =>[
  'mode' =>'create',
  'message' =>'An employee is required.',
  ],
 ->requirePresence('title')
  ->notEmptyString('title', 'Please fill this field')
  ->add('title', [
  'length' =>[
  'rule' =>['minLength', 15],
  'message' =>'Titles need to be at least 15 characters long',
  ]
  ]),
  'Feedback' =>[
  'mode' =>'update',
  'message' =>'The feedback state is required.',
  ]
 ]); 

In the above code, we have used multiple mode of requirePresence for validate the data.



ADVERTISEMENT
ADVERTISEMENT