7: Validate

Posted under » CakePHP on 12 Dec 2018

Up until this point our Articles had no input validation done. Lets fix that by using a validator:

// src/Model/Table/ArticlesTable.php
// add this
use Cake\Validation\Validator;
// Add the following method.
public function validationDefault(Validator $validator)
  {
   $validator
   ->notEmpty('title')
   ->minLength('title', 10)
   ->maxLength('title', 255)
   ->notEmpty('body')
   ->minLength('body', 10);
   return $validator;
  }

The validationDefault() method tells CakePHP how to validate your data when the save() method is called. Here, we’ve specified that both the title, and body fields must not be empty, and have certain length constraints.

CakePHP’s validation engine provides a suite of frequently used rules for tasks like email addresses, IP addresses etc. and the flexibility for adding your own validation rules.

Now that your validation rules are in place, use the app to try to add an article with an empty title or body to see how it works. Since we’ve used the Cake\View\Helper\FormHelper::control() method of the FormHelper to create our form elements, our validation error messages will be shown automatically.

Next we learn how to delete a record.

web security linux ubuntu GIT svn Raspberry apache mysql php drupal cake symfony javascript Ajax css