Validation

The validation package in CakePHP provides features to build validators that canvalidate arbitrary arrays of data with ease. You can find a list of availableValidation rules in the API.

Creating Validators

  • class Cake\Validation\Validator
  • Validator objects define the rules that apply to a set of fields.Validator objects contain a mapping between fields and validation sets. Inturn, the validation sets contain a collection of rules that apply to the fieldthey are attached to. Creating a validator is simple:
  1. use Cake\Validation\Validator;
  2.  
  3. $validator = new Validator();

Once created, you can start defining sets of rules for the fields you want tovalidate:

  1. $validator
  2. ->requirePresence('title')
  3. ->notEmpty('title', 'Please fill this field')
  4. ->add('title', [
  5. 'length' => [
  6. 'rule' => ['minLength', 10],
  7. 'message' => 'Titles need to be at least 10 characters long',
  8. ]
  9. ])
  10. ->allowEmptyDateTime('published')
  11. ->add('published', 'boolean', [
  12. 'rule' => 'boolean'
  13. ])
  14. ->requirePresence('body')
  15. ->add('body', 'length', [
  16. 'rule' => ['minLength', 50],
  17. 'message' => 'Articles must have a substantial body.'
  18. ]);

As seen in the example above, validators are built with a fluent interface thatallows you to define rules for each field you want to validate.

There were a few methods called in the example above, so let’s go over thevarious features. The add() method allows you to add new rules toa validator. You can either add rules individually or in groups as seen above.

Requiring Field Presence

The requirePresence() method requires the field to be present in anyvalidated array. If the field is absent, validation will fail. TherequirePresence() method has 4 modes:

  • true The field’s presence is always required.
  • false The field’s presence is not required.
  • create The field’s presence is required when validating a createoperation.
  • update The field’s presence is required when validating an updateoperation.
    By default, true is used. Key presence is checked by usingarray_key_exists() so that null values will count as present. You can setthe mode using the second parameter:
  1. $validator->requirePresence('author_id', 'create');

If you have multiple fields that are required, you can define them as a list:

  1. // Define multiple fields for create
  2. $validator->requirePresence(['author_id', 'title'], 'create');
  3.  
  4. // Define multiple fields for mixed modes
  5. $validator->requirePresence([
  6. 'author_id' => [
  7. 'mode' => 'create',
  8. 'message' => 'An author is required.',
  9. ],
  10. 'published' => [
  11. 'mode' => 'update',
  12. 'message' => 'The published state is required.',
  13. ]
  14. ]);

New in version 3.3.0: requirePresence() accepts an array of fields as of 3.3.0

Allowing Empty Fields

Validators offer several methods to control which fields accept empty values andwhich empty values are accepted and not forwarded to other validation rules forthe named field. CakePHP provides empty value support for five different shapesof data:

  • allowEmptyString() Should be used when you want to only acceptan empty string.
  • allowEmptyArray() Should be used when you want to accept an array.
  • allowEmptyDate() Should be used when you want to accept an empty string,or an array that is marshalled into a date field.
  • allowEmptyTime() Should be used when you want to accept an empty string,or an array that is marshalled into a time field.
  • allowEmptyDateTime() Should be used when you want to accept an emptystring or an array that is marshalled into a datetime or timestamp field.
  • allowEmptyFile() Should be used when you want to accept an array thatis contains an empty uploaded file.
    You can also use notEmpty() to mark a field invalid if any ‘empty’ value isused. In general, it is recommended that you do not use notEmpty() and use morespecific validators instead.

The allowEmpty* methods support a mode parameter that allows you to controlwhen a field can or cannot be empty:

  • false The field is not allowed to be empty.
  • create The field can be empty when validating a createoperation.
  • update The field can be empty when validating an updateoperation.
    An example of these methods in action is:
  1. // Prior to 3.7 you must use allowEmpty() or notEmpty().
  2. $validator->allowEmptyDateTime('published')
  3. ->allowEmptyString('title', false, 'Title cannot be empty')
  4. ->allowEmptyString('body', 'update', 'Body cannot be empty')
  5. ->allowEmptyFile('header_image', 'update');
  6. ->allowEmptyDateTime('posted', 'update');

Adding Validation Rules

The Validator class provides methods that make building validators simpleand expressive. For example adding validation rules to a username could looklike:

  1. $validator = new Validator();
  2. $validator
  3. ->email('username')
  4. ->ascii('username')
  5. ->lengthBetween('username', [4, 8]);

See the Validator API documentation for thefull set of validator methods.

New in version 3.2: Rule building methods were added in 3.2.0

Using Custom Validation Rules

In addition to using methods on the Validator, and coming from providers, youcan also use any callable, including anonymous functions, as validation rules:

  1. // Use a global function
  2. $validator->add('title', 'custom', [
  3. 'rule' => 'validate_title',
  4. 'message' => 'The title is not valid'
  5. ]);
  6.  
  7. // Use an array callable that is not in a provider
  8. $validator->add('title', 'custom', [
  9. 'rule' => [$this, 'method'],
  10. 'message' => 'The title is not valid'
  11. ]);
  12.  
  13. // Use a closure
  14. $extra = 'Some additional value needed inside the closure';
  15. $validator->add('title', 'custom', [
  16. 'rule' => function ($value, $context) use ($extra) {
  17. // Custom logic that returns true/false
  18. },
  19. 'message' => 'The title is not valid'
  20. ]);
  21.  
  22. // Use a rule from a custom provider
  23. $validator->add('title', 'custom', [
  24. 'rule' => 'customRule',
  25. 'provider' => 'custom',
  26. 'message' => 'The title is not unique enough'
  27. ]);

Closures or callable methods will receive 2 arguments when called. The firstwill be the value for the field being validated. The second is a context arraycontaining data related to the validation process:

  • data: The original data passed to the validation method, useful if youplan to create rules comparing values.
  • providers: The complete list of rule provider objects, useful if youneed to create complex rules by calling multiple providers.
  • newRecord: Whether the validation call is for a new record ora preexisting one.
    If you need to pass additional data to your validation methods such as thecurrent user’s id, you can use a custom dynamic provider from your controller.
  1. $this->Examples->validator('default')->provider('passed', [
  2. 'count' => $countFromController,
  3. 'userid' => $this->Auth->user('id')
  4. ]);

Then ensure that your validation method has the second context parameter.

  1. public function customValidationMethod($check, array $context)
  2. {
  3. $userid = $context['providers']['passed']['userid'];
  4. }

Closures should return boolean true if the validation passes. If it fails,return boolean false or for a custom error message return a string, see theConditional/Dynamic Error Messagessection for further details.

Conditional/Dynamic Error Messages

Validation rule methods, being it custom callables,or methods supplied by providers, can eitherreturn a boolean, indicating whether the validation succeeded, or they can returna string, which means that the validation failed, and that the returned stringshould be used as the error message.

Possible existing error messages defined via the message option will beoverwritten by the ones returned from the validation rule method:

  1. $validator->add('length', 'custom', [
  2. 'rule' => function ($value, $context) {
  3. if (!$value) {
  4. return false;
  5. }
  6.  
  7. if ($value < 10) {
  8. return 'Error message when value is less than 10';
  9. }
  10.  
  11. if ($value > 20) {
  12. return 'Error message when value is greater than 20';
  13. }
  14.  
  15. return true;
  16. },
  17. 'message' => 'Generic error message used when `false` is returned'
  18. ]);

Conditional Validation

When defining validation rules, you can use the on key to define whena validation rule should be applied. If left undefined, the rule will always beapplied. Other valid values are create and update. Using one of thesevalues will make the rule apply to only create or update operations.

Additionally, you can provide a callable function that will determine whether ornot a particular rule should be applied:

  1. $validator->add('picture', 'file', [
  2. 'rule' => ['mimeType', ['image/jpeg', 'image/png']],
  3. 'on' => function ($context) {
  4. return !empty($context['data']['show_profile_picture']);
  5. }
  6. ]);

You can access the other submitted field values using the $context['data']array.The above example will make the rule for ‘picture’ optional depending on whetherthe value for show_profile_picture is empty. You could also use theuploadedFile validation rule to create optional file upload inputs:

  1. $validator->add('picture', 'file', [
  2. 'rule' => ['uploadedFile', ['optional' => true]],
  3. ]);

The allowEmpty*, notEmpty() and requirePresence() methods will alsoaccept a callback function as their last argument. If present, the callbackdetermines whether or not the rule should be applied. For example, a field issometimes allowed to be empty:

  1. $validator->allowEmptyString('tax', function ($context) {
  2. return !$context['data']['is_taxable'];
  3. });

Likewise, a field can be required to be populated when certain conditions aremet:

  1. $validator->notEmpty('email_frequency', 'This field is required', function ($context) {
  2. return !empty($context['data']['wants_newsletter']);
  3. });

In the above example, the email_frequency field cannot be left empty if thethe user wants to receive the newsletter.

Further it’s also possible to require a field to be present under certainconditions only:

  1. $validator->requirePresence('full_name', function ($context) {
  2. if (isset($context['data']['action'])) {
  3. return $context['data']['action'] === 'subscribe';
  4. }
  5. return false;
  6. });
  7. $validator->requirePresence('email');

This would require the full_name field to be present only in case the userwants to create a subscription, while the email field would always berequired, since it would also be needed when canceling a subscription.

New in version 3.1.1: The callable support for requirePresence() was added in 3.1.1

Marking Rules as the Last to Run

When fields have multiple rules, each validation rule will be run even if theprevious one has failed. This allows you to collect as many validation errors asyou can in a single pass. However, if you want to stop execution aftera specific rule has failed, you can set the last option to true:

  1. $validator = new Validator();
  2. $validator
  3. ->add('body', [
  4. 'minLength' => [
  5. 'rule' => ['minLength', 10],
  6. 'last' => true,
  7. 'message' => 'Comments must have a substantial body.'
  8. ],
  9. 'maxLength' => [
  10. 'rule' => ['maxLength', 250],
  11. 'message' => 'Comments cannot be too long.'
  12. ]
  13. ]);

If the minLength rule fails in the example above, the maxLength rule will not berun.

Adding Validation Providers

The Validator, ValidationSet and ValidationRule classes do notprovide any validation methods themselves. Validation rules come from‘providers’. You can bind any number of providers to a Validator object.Validator instances come with a ‘default’ provider setup automatically. Thedefault provider is mapped to the Validation\Validationclass. This makes it simple to use the methods on that class as validationrules. When using Validators and the ORM together, additional providers areconfigured for the table and entity objects. You can use the setProvider()method to add any additional providers your application needs:

  1. $validator = new Validator();
  2.  
  3. // Use an object instance.
  4. $validator->setProvider('custom', $myObject);
  5.  
  6. // Use a class name. Methods must be static.
  7. $validator->setProvider('custom', 'App\Model\Validation');

Validation providers can be objects, or class names. If a class name is used themethods must be static. To use a provider other than ‘default’, be sure to setthe provider key in your rule:

  1. // Use a rule from the table provider
  2. $validator->add('title', 'custom', [
  3. 'rule' => 'customTableMethod',
  4. 'provider' => 'table'
  5. ]);

If you wish to add a provider to all Validator objects that are createdin the future, you can use the addDefaultProvider() method as follows:

  1. use Cake\Validation\Validator;
  2.  
  3. // Use an object instance.
  4. Validator::addDefaultProvider('custom', $myObject);
  5.  
  6. // Use a class name. Methods must be static.
  7. Validator::addDefaultProvider('custom', 'App\Model\Validation');

Note

DefaultProviders must be added before the Validator object is createdtherefore config/bootstrap.php is the best place to set up yourdefault providers.

New in version 3.5.0.

You can use the Localized plugin toget providers based on countries. With this plugin, you’ll be able to validatemodel fields, depending on a country, ie:

  1. namespace App\Model\Table;
  2.  
  3. use Cake\ORM\Table;
  4. use Cake\Validation\Validator;
  5.  
  6. class PostsTable extends Table
  7. {
  8. public function validationDefault(Validator $validator)
  9. {
  10. // add the provider to the validator
  11. $validator->setProvider('fr', 'Localized\Validation\FrValidation');
  12. // use the provider in a field validation rule
  13. $validator->add('phoneField', 'myCustomRuleNameForPhone', [
  14. 'rule' => 'phone',
  15. 'provider' => 'fr'
  16. ]);
  17.  
  18. return $validator;
  19. }
  20. }

The localized plugin uses the two letter ISO code of the countries forvalidation, like en, fr, de.

There are a few methods that are common to all classes, defined through theValidationInterface interface:

  1. phone() to check a phone number
  2. postal() to check a postal code
  3. personId() to check a country specific person ID

Nesting Validators

New in version 3.0.5.

When validating Modelless Forms with nested data, or when workingwith models that contain array data types, it is necessary to validate thenested data you have. CakePHP makes it simple to add validators to specificattributes. For example, assume you are working with a non-relational databaseand need to store an article and its comments:

  1. $data = [
  2. 'title' => 'Best article',
  3. 'comments' => [
  4. ['comment' => '']
  5. ]
  6. ];

To validate the comments you would use a nested validator:

  1. $validator = new Validator();
  2. $validator->add('title', 'not-blank', ['rule' => 'notBlank']);
  3.  
  4. $commentValidator = new Validator();
  5. $commentValidator->add('comment', 'not-blank', ['rule' => 'notBlank']);
  6.  
  7. // Connect the nested validators.
  8. $validator->addNestedMany('comments', $commentValidator);
  9.  
  10. // Get all errors including those from nested validators.
  11. $validator->errors($data);

You can create 1:1 ‘relationships’ with addNested() and 1:N ‘relationships’with addNestedMany(). With both methods, the nested validator’s errors willcontribute to the parent validator’s errors and influence the final result.Like other validator features, nested validators support error messages andconditional application:

  1. $validator->addNestedMany(
  2. 'comments',
  3. $commentValidator,
  4. 'Invalid comment',
  5. 'create'
  6. );

The error message for a nested validator can be found in the _nested key.

New in version 3.6.0: message and conditions for nested validators were added.

Creating Reusable Validators

While defining validators inline where they are used makes for good examplecode, it doesn’t lead to maintainable applications. Instead, you shouldcreate Validator sub-classes for your reusable validation logic:

  1. // In src/Model/Validation/ContactValidator.php
  2. namespace App\Model\Validation;
  3.  
  4. use Cake\Validation\Validator;
  5.  
  6. class ContactValidator extends Validator
  7. {
  8. public function __construct()
  9. {
  10. parent::__construct();
  11. // Add validation rules here.
  12. }
  13. }

Validating Data

Now that you’ve created a validator and added the rules you want to it, you canstart using it to validate data. Validators are able to validate arraydata. For example, if you wanted to validate a contact form before creating andsending an email you could do the following:

  1. use Cake\Validation\Validator;
  2.  
  3. $validator = new Validator();
  4. $validator
  5. ->requirePresence('email')
  6. ->add('email', 'validFormat', [
  7. 'rule' => 'email',
  8. 'message' => 'E-mail must be valid'
  9. ])
  10. ->requirePresence('name')
  11. ->notEmpty('name', 'We need your name.')
  12. ->requirePresence('comment')
  13. ->notEmpty('comment', 'You need to give a comment.');
  14.  
  15. $errors = $validator->errors($this->request->getData());
  16. if (empty($errors)) {
  17. // Send an email.
  18. }

The errors() method will return a non-empty array when there are validationfailures. The returned array of errors will be structured like:

  1. $errors = [
  2. 'email' => ['E-mail must be valid']
  3. ];

If you have multiple errors on a single field, an array of error messages willbe returned per field. By default the errors() method applies rules forthe ‘create’ mode. If you’d like to apply ‘update’ rules you can do thefollowing:

  1. $errors = $validator->errors($this->request->getData(), false);
  2. if (empty($errors)) {
  3. // Send an email.
  4. }

Note

If you need to validate entities you should use methods likeORM\Table::newEntity(),ORM\Table::newEntities(),ORM\Table::patchEntity(),ORM\Table::patchEntities() orORM\Table::save() as they are designed for that.

Validating Entities

While entities are validated as they are saved, you may also want to validateentities before attempting to do any saving. Validating entities beforesaving is done automatically when using the newEntity(), newEntities(),patchEntity() or patchEntities():

  1. // In the ArticlesController class
  2. $article = $this->Articles->newEntity($this->request->getData());
  3. if ($article->errors()) {
  4. // Do work to show error messages.
  5. }

Similarly, when you need to pre-validate multiple entities at a time, you canuse the newEntities() method:

  1. // In the ArticlesController class
  2. $entities = $this->Articles->newEntities($this->request->getData());
  3. foreach ($entities as $entity) {
  4. if (!$entity->errors()) {
  5. $this->Articles->save($entity);
  6. }
  7. }

The newEntity(), patchEntity(), newEntities() and patchEntities()methods allow you to specify which associations are validated, and whichvalidation sets to apply using the options parameter:

  1. $valid = $this->Articles->newEntity($article, [
  2. 'associated' => [
  3. 'Comments' => [
  4. 'associated' => ['User'],
  5. 'validate' => 'special',
  6. ]
  7. ]
  8. ]);

Validation is commonly used for user-facing forms or interfaces, and thus it isnot limited to only validating columns in the table schema. However,maintaining integrity of data regardless where it came from is important. Tosolve this problem CakePHP offers a second level of validation which is called“application rules”. You can read more about them in theApplying Application Rules section.

Core Validation Rules

CakePHP provides a basic suite of validation methods in the Validationclass. The Validation class contains a variety of static methods that providevalidators for several common validation situations.

The API documentation for theValidation class provides a good list of the validation rules that areavailable, and their basic usage.

Some of the validation methods accept additional parameters to define boundaryconditions or valid options. You can provide these boundary conditions andoptions as follows:

  1. $validator = new Validator();
  2. $validator
  3. ->add('title', 'minLength', [
  4. 'rule' => ['minLength', 10]
  5. ])
  6. ->add('rating', 'validValue', [
  7. 'rule' => ['range', 1, 5]
  8. ]);

Core rules that take additional parameters should have an array for therule key that contains the rule as the first element, and the additionalparameters as the remaining parameters.