Class Validator
Validator object encapsulates all methods related to data validations for a model It also provides an API to dynamically change validation rules for each model field.
Implements ArrayAccess to easily modify rules in the set
Constants
-
string
NESTED ¶'_nested'
Used to flag nested rules created with addNested() and addNestedMany()
Property Summary
-
$_allowEmptyMessages protected
array
Contains the validation messages associated with checking the emptiness for each corresponding field.
-
$_fields protected
array
Holds the ValidationSet objects array
-
$_presenceMessages protected
array
Contains the validation messages associated with checking the presence for each corresponding field.
-
$_providers protected
array
An associative array of objects or classes containing methods used for validation
-
$_useI18n protected
bool
Whether or not to use I18n functions for translating default error messages
Method Summary
-
__construct() public
Constructor
-
__debugInfo() public
Get the printable version of this object.
-
_canBeEmpty() protected
Returns whether the field can be left blank according to
allowEmpty
-
_checkPresence() protected
Returns false if any validation for the passed rule set should be stopped due to the field missing in the data array
-
_fieldIsEmpty() protected
Returns true if the field is empty in the passed data array
-
_processRules() protected
Iterates over each rule in the validation set and collects the errors resulting from executing them
-
add() public
Adds a new rule to a field's rule set. If second argument is an array then rules list for the field will be replaced with second argument and third argument will be ignored.
-
addNested() public
Adds a nested validator.
-
addNestedMany() public
Adds a nested validator.
-
allowEmpty() public
Allows a field to be empty.
-
count() public
Returns the number of fields having validation rules
-
errors() public
Returns an array of fields that have failed validation. On the current model. This method will actually run validation rules over data, not just return the messages.
-
field() public
Returns a ValidationSet object containing all validation rules for a field, if passed a ValidationSet as second argument, it will replace any other rule set defined before
-
getIterator() public
Returns an iterator for each of the fields to be validated
-
hasField() public
Check whether or not a validator contains any rules for the given field.
-
isEmptyAllowed() public
Returns whether or not a field can be left empty for a new or already existing record.
-
isPresenceRequired() public
Returns whether or not a field can be left out for a new or already existing record.
-
notEmpty() public
Sets a field to require a non-empty value.
-
offsetExists() public
Returns whether a rule set is defined for a field or not
-
offsetGet() public
Returns the rule set for a field
-
offsetSet() public
Sets the rule set for a field
-
offsetUnset() public
Unsets the rule set for a field
-
provider() public
Associates an object to a name so it can be used as a provider. Providers are objects or class names that can contain methods used during validation of for deciding whether a validation rule can be applied. All validation methods, when called will receive the full list of providers stored in this validator.
-
providers() public
Get the list of providers in this validator.
-
remove() public
Removes a rule from the set by its name
-
requirePresence() public
Sets whether a field is required to be present in data array.
Method Detail
_canBeEmpty() ¶ protected
_canBeEmpty(Cake\Validation\ValidationSet $field, array $context): bool
Returns whether the field can be left blank according to allowEmpty
Parameters
-
Cake\Validation\ValidationSet
$field the set of rules for a field
-
array
$context a key value list of data containing the validation context.
Returns
bool
_checkPresence() ¶ protected
_checkPresence(Cake\Validation\ValidationSet $field, array $context): bool
Returns false if any validation for the passed rule set should be stopped due to the field missing in the data array
Parameters
-
Cake\Validation\ValidationSet
$field The set of rules for a field.
-
array
$context A key value list of data containing the validation context.
Returns
bool
_fieldIsEmpty() ¶ protected
_fieldIsEmpty(mixed $data): bool
Returns true if the field is empty in the passed data array
Parameters
-
mixed
$data value to check against
Returns
bool
_processRules() ¶ protected
_processRules(string $field, Cake\Validation\ValidationSet $rules, array $data, bool $newRecord): array
Iterates over each rule in the validation set and collects the errors resulting from executing them
Parameters
-
string
$field The name of the field that is being processed
-
Cake\Validation\ValidationSet
$rules the list of rules for a field
-
array
$data the full data passed to the validator
-
bool
$newRecord whether is it a new record or an existing one
Returns
array
add() ¶ public
add(string $field, array|string $name, array|Cake\Validation\ValidationRule $rule = []): $this
Adds a new rule to a field's rule set. If second argument is an array then rules list for the field will be replaced with second argument and third argument will be ignored.
Example:
$validator
->add('title', 'required', ['rule' => 'notBlank'])
->add('user_id', 'valid', ['rule' => 'numeric', 'message' => 'Invalid User'])
$validator->add('password', [
'size' => ['rule' => ['lengthBetween', 8, 20]],
'hasSpecialCharacter' => ['rule' => 'validateSpecialchar', 'message' => 'not valid']
]);
Parameters
-
string
$field The name of the field from which the rule will be removed
-
array|string
$name The alias for a single rule or multiple rules array
-
array|Cake\Validation\ValidationRule
$rule optional the rule to add
Returns
$this
addNested() ¶ public
addNested(string $field, Cake\Validation\Validator $validator): $this
Adds a nested validator.
Nesting validators allows you to define validators for array types. For example, nested validators are ideal when you want to validate a sub-document, or complex array type.
This method assumes that the sub-document has a 1:1 relationship with the parent.
The providers of the parent validator will be synced into the nested validator, when errors are checked. This ensures that any validation rule providers connected in the parent will have the same values in the nested validator when rules are evaluated.
Parameters
-
string
$field The root field for the nested validator.
-
Cake\Validation\Validator
$validator The nested validator.
Returns
$this
addNestedMany() ¶ public
addNestedMany(string $field, Cake\Validation\Validator $validator): $this
Adds a nested validator.
Nesting validators allows you to define validators for array types. For example, nested validators are ideal when you want to validate many similar sub-documents or complex array types.
This method assumes that the sub-document has a 1:N relationship with the parent.
The providers of the parent validator will be synced into the nested validator, when errors are checked. This ensures that any validation rule providers connected in the parent will have the same values in the nested validator when rules are evaluated.
Parameters
-
string
$field The root field for the nested validator.
-
Cake\Validation\Validator
$validator The nested validator.
Returns
$this
allowEmpty() ¶ public
allowEmpty(string $field, bool|string|callable $when = true): $this
Allows a field to be empty.
This is the opposite of notEmpty() which requires a field to not be empty. By using $mode equal to 'create' or 'update', you can allow fields to be empty when records are first created, or when they are updated.
Example:
$validator->allowEmpty('email'); // Email can be empty
$validator->allowEmpty('email', 'create'); // Email can be empty on create
$validator->allowEmpty('email', 'update'); // Email can be empty on update
It is possible to conditionally allow emptiness on a field by passing a callback as a second argument. The callback will receive the validation context array as argument:
$validator->allowEmpty('email', function ($context) {
return !$context['newRecord'] || $context['data']['role'] === 'admin';
});
This method will correctly detect empty file uploads and date/time/datetime fields.
Because this and notEmpty()
modify the same internal state, the last
method called will take precedence.
Parameters
-
string
$field the name of the field
-
bool|string|callable
$when optional Indicates when the field is allowed to be empty Valid values are true (always), 'create', 'update'. If a callable is passed then the field will allowed to be empty only when the callback returns true.
Returns
$this
errors() ¶ public
errors(array $data, bool $newRecord = true): array
Returns an array of fields that have failed validation. On the current model. This method will actually run validation rules over data, not just return the messages.
Parameters
-
array
$data The data to be checked for errors
-
bool
$newRecord optional whether the data to be validated is new or to be updated.
Returns
array
field() ¶ public
field(string $name, Cake\Validation\ValidationSet|null $set = null): Cake\Validation\ValidationSet
Returns a ValidationSet object containing all validation rules for a field, if passed a ValidationSet as second argument, it will replace any other rule set defined before
Parameters
-
string
$name [optional] The fieldname to fetch.
-
Cake\Validation\ValidationSet|null
$set optional The set of rules for field
Returns
Cake\Validation\ValidationSet
getIterator() ¶ public
getIterator(): ArrayIterator
Returns an iterator for each of the fields to be validated
Returns
ArrayIterator
hasField() ¶ public
hasField(string $name): bool
Check whether or not a validator contains any rules for the given field.
Parameters
-
string
$name The field name to check.
Returns
bool
isEmptyAllowed() ¶ public
isEmptyAllowed(string $field, bool $newRecord): bool
Returns whether or not a field can be left empty for a new or already existing record.
Parameters
-
string
$field Field name.
-
bool
$newRecord whether the data to be validated is new or to be updated.
Returns
bool
isPresenceRequired() ¶ public
isPresenceRequired(string $field, bool $newRecord): bool
Returns whether or not a field can be left out for a new or already existing record.
Parameters
-
string
$field Field name.
-
bool
$newRecord Whether the data to be validated is new or to be updated.
Returns
bool
notEmpty() ¶ public
notEmpty(string $field, string $message = null, bool|string|callable $when = false): $this
Sets a field to require a non-empty value.
This is the opposite of allowEmpty() which allows a field to be empty. By using $mode equal to 'create' or 'update', you can make fields required when records are first created, or when they are updated.
Example:
$message = 'This field cannot be empty';
$validator->notEmpty('email'); // Email cannot be empty
$validator->notEmpty('email', $message, 'create'); // Email can be empty on update
$validator->notEmpty('email', $message, 'update'); // Email can be empty on create
It is possible to conditionally disallow emptiness on a field by passing a callback as the third argument. The callback will receive the validation context array as argument:
$validator->notEmpty('email', 'Email is required', function ($context) {
return $context['newRecord'] && $context['data']['role'] !== 'admin';
});
Because this and allowEmpty()
modify the same internal state, the last
method called will take precedence.
Parameters
-
string
$field the name of the field
-
string
$message optional The validation message to show if the field is not
-
bool|string|callable
$when optional Indicates when the field is not allowed to be empty. Valid values are true (always), 'create', 'update'. If a callable is passed then the field will allowed be empty only when the callback returns false.
Returns
$this
offsetExists() ¶ public
offsetExists(string $field): bool
Returns whether a rule set is defined for a field or not
Parameters
-
string
$field name of the field to check
Returns
bool
offsetGet() ¶ public
offsetGet(string $field): Cake\Validation\ValidationSet
Returns the rule set for a field
Parameters
-
string
$field name of the field to check
Returns
Cake\Validation\ValidationSet
offsetSet() ¶ public
offsetSet(string $field, array|Cake\Validation\ValidationSet $rules): void
Sets the rule set for a field
Parameters
-
string
$field name of the field to set
-
array|Cake\Validation\ValidationSet
$rules set of rules to apply to field
Returns
void
offsetUnset() ¶ public
offsetUnset(string $field): void
Unsets the rule set for a field
Parameters
-
string
$field name of the field to unset
Returns
void
provider() ¶ public
provider(string $name, null|object|string $object = null): $this|object|string|null
Associates an object to a name so it can be used as a provider. Providers are objects or class names that can contain methods used during validation of for deciding whether a validation rule can be applied. All validation methods, when called will receive the full list of providers stored in this validator.
If called with no arguments, it will return the provider stored under that name if it exists, otherwise it returns this instance of chaining.
Parameters
-
string
$name The name under which the provider should be set.
-
null|object|string
$object optional Provider object or class name.
Returns
$this|object|string|null
remove() ¶ public
remove(string $field, string|null $rule = null): $this
Removes a rule from the set by its name
Example:
$validator
->remove('title', 'required')
->remove('user_id')
Parameters
-
string
$field The name of the field from which the rule will be removed
-
string|null
$rule optional the name of the rule to be removed
Returns
$this
requirePresence() ¶ public
requirePresence(string $field, bool|string|callable $mode = true, string|null $message = null): $this
Sets whether a field is required to be present in data array.
Parameters
-
string
$field the name of the field
-
bool|string|callable
$mode optional Valid values are true, false, 'create', 'update'. If a callable is passed then the field will be required only when the callback returns true.
-
string|null
$message optional The message to show if the field presence validation fails.
Returns
$this
Property Detail
$_allowEmptyMessages ¶ protected
Contains the validation messages associated with checking the emptiness for each corresponding field.
Type
array
$_presenceMessages ¶ protected
Contains the validation messages associated with checking the presence for each corresponding field.
Type
array
$_providers ¶ protected
An associative array of objects or classes containing methods used for validation
Type
array
$_useI18n ¶ protected
Whether or not to use I18n functions for translating default error messages
Type
bool