Now that you have seen the big picture of data validation, let’s take a look at how to define these rules in the model. There are three different approaches: simple array, single rule per column, multiple rules per column.
As the name suggests, this is the simplest way to define validation rules. The standard syntax for defining rules in this method is:
‘fieldName’ is the name of the column to which the rule applies, and ‘ruleName’ is a predefined rule name, such as ‘alphaNumeric’, ‘email’ or ‘isUnique’.
For example, to ensure that the user provides a properly formatted email address, you can use the following rule:
This definition method has better control over the work of the verification rules. Before we discuss this, let’s look at the standard usage of adding a rule to a single column:
The ‘rule’ key is required. If only 'required' => true is set, form validation will not work correctly. Because 'required' is not an actual rule.
As you can see, each column (only one is shown above) is associated with an array containing the following five keys: 'rule', 'required', 'allowEmpty', 'on' and 'message' . Let's take a closer look at these keys.
The ‘rule’ method defines the validation aspect and specifies a value or an array. This particular ‘rule’ may be the name of a method in the model, the name of a method in the core Validation class, or a regular expression. To learn more about the default rules, see Kernel Verification Rules.
If rule does not contain any parameters, 'rule' can be a single value, for example:
If rule contains parameters (such as max, min or range), 'rule' will be an array:
Remember, when defining rules in an array, the 'rule' key is required.
This key accepts a logical value, create or update. Setting this to true will make this column always required. Setting to create or update will make this column required only for update or create operations. If 'required' equals true, this column must be provided in the array. For example, if the following verification rules are defined:
The data passed to the model's save() method must contain the data provided to the login column. If it does not exist, the verification fails. The default value for this key is logical false.
required => true is not the same thing as notEmpty() in the validation rules. required => true means that this array key must be provided - does not mean that it must have a value. If the dataset is not provided, the validation fails, but may succeed if a null value ('') is submitted (this depends on the detailed definition of the rule).
Changed in version 2.1: Added support for create and update.
If set to false, the field value must be nonempty, where "nonempty" is defined as !empty($value) || is_numeric($value). For numerical detection, CakePHP considers it correct when $value is 0.
The difference between required and allowEmpty can cause confusion. 'required' => true means that the model cannot be saved without providing a key with this column in $this->data; and 'allowEmpty' => false, like the search described above, ensures the value of this column Must be non-null.
The ‘on’ key can be set to ‘update’ or ‘create’. It provides a mechanism that allows some rules to be applied during the creation of new records or the process of updating records.
If a rule is defined as ‘on’ => ‘create’, this rule is only effective during the process of creating new records. Similarly, if it is defined as 'on' => 'update', it will only be effective during the process of updating records.
The default value of ‘on’ is null. When ‘on’ is null, this rule takes effect during both creation and update processes.
The message key is the displayed message when the rule customizes the verification error:
The above technology provides us with greater flexibility than simple rule allocation. Going one step further, we can obtain more detailed data verification control. Below we introduce a technique that allows us to assign multiple rules to each column.
If you want to assign multiple validation rules to a single column, the basic writing method is as follows:
5
9
As you can see, this is very similar to what we did in the previous section. There, there is only one validation parameter array per column. Here, each ‘fieldName’ is an index into a regular array. Each ‘ruleName’ contains an array of validation parameters.
4
8
The above example defines two rules for the login column: loginRule-1 and loginRule-2. As you can see, the identifiers for each rule are named arbitrarily.
When defining multiple rules for a single column, the 'required' and 'allowEmpty' keys only need to be used once in the first rule.
For the case where there are multiple rules for each column, by default, if a rule fails to verify and returns an error message, subsequent rules for this column will not be calculated. If you want a rule to continue validation even if it fails, set the last key of the rule to false.
In the example below, even if "rule1" fails, "rule2" will still be evaluated, and all error messages will be returned if "rule2" also fails:
4
6
9
When specifying validation rules using an array, the message key does not need to be used. Consider the following example:
If the alphaNumeric rule fails, the rule’s key ‘Only alphabets and numbers allowed’ will be returned as an error message since the message key is not set.
If you can’t find the required verification rules, you can customize them. There are two ways to customize: customize regular expressions, or create custom validation methods.
If the required verification method can be completed through regular expression matching, you can customize the expression as the verification rule for the column:
The above example checks whether login contains only letters and integers and must not be less than 3 characters.
Regular expressions in "rule" must be enclosed in slashes (/). The optional 'i' at the end indicates that the regular expression is case-insensitive.
Sometimes just using regular patterns to verify data is not enough. For example, if you want to ensure that a promotional code can only be used 25 times, you need to add your own verification method. The example is as follows:
5
The current column being verified is passed to the function. As the first parameter of the function, it is an associative array composed of the column name as the key and the data from post as the value.
If you want to pass additional parameters to the check function, add an element to the ‘rule’ array and handle them as extended parameters in the function (after the main parameter $check).
The validation function can be placed in the model (like the example above), or it can be placed in the behavior implemented by the model. Includes mapping methods.
Model/behavior methods are verified first, taking precedence over methods in the Validation class. This means that existing validation methods (such as alphaNumeric()) can be overridden at the application level (by adding methods in the AppModel) or at the model level.
Be careful when writing validation rules that can apply to multiple columns, extracting column values from the $check array. The $check array is composed of the form domain name as the key and the form field value as the value. The entire record stored in the $this->data member variable is verified.
5
6 'message' => 'Slug can only be letters, numbers, dash and underscore'
The visibility of custom verification methods must be public. Protected and private level verification methods are not supported.
If the rule is valid, this method returns true. If verification fails, false is returned. Another valid return value is a string that is the error message to be displayed. Returning a string means validation failed. This string will overwrite the information set in the $validate array and will be displayed in the view's form as the reason why the column is invalid.
Using the $validate attribute to define validation rules is a good way to define static rules for each model. But sometimes you need to dynamically add, change, or delete validation rules from a predefined rule set.
All validation rules are stored in the ModelValidator object, which holds each rule set for each column in the model. It is simple to define new validation rules by notifying this object to store new validation methods for the desired columns.
2.2 new features.
ModelValidator objects provide several ways to add new columns to a set. The first is to use the add method:
This will add a single rule for the password column in the model. You can call add multiple times in a chain to create multiple required rules:
6 'size' => array(
7 'rule' => array('between', 8, 20),
8 'message' => 'Password should be at least 8 chars long'
9 )
10 ));
Or you can use this object using the array interface to directly set rules for columns:
1 $validator = $this->validator();
2 $validator['username'] = array(
3 'unique' => array(
4 'rule' => 'isUnique',
5 'required' => 'create'
6 ),
7 'alphanumeric' => array(
8 'rule' => 'alphanumeric'
9 )
10 );
Edit existing validation rules
2.2 new features.
Existing validation rules can be edited using the validator object. There are several ways to modify existing rules, append methods to a column, or completely delete a rule from a column rule set:
1 // In model class
2 $this->validator()->getField('password')->setRule('required', array(
3 'rule' => 'required',
4 'required' => true
5 ));
You can also use a similar method to completely replace all the rules of a column:
1 // In model class
2 $this->validator()->getField('password')->setRules(array(
3 'required' => array(...),
4 'otherRule' => array(...)
5 ));
If you just want to get back a single attribute in the rule, you can directly set the attributes of the CakeValidationRule object:
1 // In model class
2 $this->validator()->getField('password')
3 ->getRule('required')->message = 'This field cannot be left blank';
Properties in CakeValidationRule are named by valid array keys that define the corresponding rule in the model using the $validate attribute.
When adding rules to the rule set, you can also use the array interface to edit existing rules:
1 $validator = $this->validator();
2 $validator['username']['unique'] = array(
3 'rule' => 'isUnique',
4 'required' => 'create'
5 );
6
7 $validator['username']['unique']->last = true;
8 $validator['username']['unique']->message = 'Name already taken';
Remove rule from rule set
2.2 new features.
It is possible to completely delete all rules for a column and to delete only a single rule in a column rule set:
1 // Completely delete all rules for a column
2 $this->validator()->remove('username');
3
4 // Remove the 'required' rule from password
5 $this->validator()->remove('password', 'required');
You can also delete rules from a rule set using the array interface:
1 $validator = $this->validator();
2 // Completely delete all rules of a column
3 unset($validator['username']);
4
5 // Remove 'required' rule from passworkd
6 unset($validator['password']['required']);
Kernel verification rules
class Validation
CakePHP’s Validation class contains many validation rules that make model data validation easier. This class contains many commonly used validation techniques that you don't need to write yourself. Below is a complete list of all rules and examples of their usage.
static Validation::alphaNumeric(mixed $check)
Column data must contain letters and numbers only.
1 public $validate = array(
2 'login' => array(
3 'rule' => 'alphaNumeric',
4 'message' => 'Usernames must only contain letters and numbers.'
5 )
6 );
static Validation::between(string $check, integer $min, integer $max)
The data length of the column must be within the specified numerical range. Both minimum and maximum values must be provided. Uses = not.:
1 public $validate = array(
2 'password' => array(
3 'rule' => array('between', 5, 15),
4 'message' => 'Passwords must be between 5 and 15 characters long.'
5 )
6 );
The length of data refers to the "number of bytes of string data". Be careful, when dealing with non-ASCII characters, the value may be greater than the number of characters.
static Validation::blank(mixed $check)
This rule is used to ensure that the column value is empty or its value contains only whitespace characters. Whitespace characters include spaces, tabs, carriage returns, and line feeds.
1 public $validate = array(
2 'id' => array(
3 'rule' => 'blank',
4 'on' => 'create'
5 )
6 );
static Validation::boolean(string $check)
Column data must be logical values. Valid values include true or false, integer value 0 or 1, string value '0' or '1'.
1 public $validate = array(
2 'myCheckbox' => array(
3 'rule' => array('boolean'),
4 'message' => 'Incorrect value for myCheckbox'
5 )
6 );
static Validation::cc(mixed $check, mixed $type = 'fast', boolean $deep = false, string $regex = null)
This rule checks if the data is a valid credit card number. It has three parameters: 'type', 'deep' and 'regex'.
The 'type' key can be assigned one of the following values: 'fast' or 'all':
amex
bankcard
diners
disc
electron
enroute
jcb
maestro
mc
solo
switch
visa
voyager
If 'type' is set to 'fast', the encoding format of the primary credit card is checked. 'type' set to 'all' validates all credit card types. You can also set 'type' to an array of types you wish to check.
The 'deep' key needs to be set to a logical value. If true, the validation rule will check the credit card's Luhn algorithm (http://en.wikipedia.org/wiki/Luhn_algorithm). The default value is false.
The 'regex' key allows providing a custom regular expression for validating credit card numbers:
1 public $validate = array(
2 'ccnumber' => array(
3 'rule' => array('cc', array('visa', 'maestro'), false, null),
4 'message' => 'The credit card number you supplied was invalid.'
5 )
6 );
static Validation::comparison(mixed $check1, string $operator = null, integer $check2 = null)
Comparison is used to compare numeric values. Supports "is greater", "isless", "greater or equal", "less or equal", "equal to" and "not equal". The following is an example:
1 public $validate = array(
2 'age' => array(
3 'rule' => array('comparison', '>=', 18),
4 'message' => 'Must be at least 18 years old to qualify.'
5 )
6 );
7
8 public $validate = array(
9 'age' => array(
10 'rule' => array('comparison', 'greater or equal', 18),
11 'message' => 'Must be at least 18 years old to qualify.'
12 )
13 );
static Validation::custom(mixed $check, string $regex = null)
for custom regular expression:
1 public $validate = array(
2 'infinite' => array(
3 'rule' => array('custom', 'u221E'),
4 'message' => 'Please enter an infinite number.'
5 )
6 );
static Validation::date(string $check, mixed $format = 'ymd', string $regex = null)
This rule ensures that submitted data is in the correct date format. You can pass a parameter (can be an array) that specifies the format of the date to be verified. This parameter can be one of the following:
‘dmy’ e.g. 27-12-2006 or 27-12-06 (the separator can be space, period, dash, slash)
‘mdy’ For example, 12-27-2006 or 12-27-06 (the separator can be space, period, dash, slash)
‘ymd’ For example, 2006-12-27 or 06-12-27 (the separator can be space, period, dash, slash)
‘dMy’ respectively 27 December 2006 or 27 Dec 2006
‘Mdy’ e.g. December 27, 2006 or Dec 27, 2006 (comma is optional)
‘My’ e.g. (December 2006 or Dec 2006)
‘my’ For example 12/2006 or 12/06 (the separator can be space, period, dash, slash)
If this key is not provided, 'ymd' will be used by default:
1 public $validate = array(
2 'born' => array(
3 'rule' => array('date', 'ymd'),
4 'message' => 'Enter a valid date in YY-MM-DD format.',
5 'allowEmpty' => true
6 )
7 );
When a lot of data needs to be stored in a specific format, you might consider accepting a wider format and converting it, rather than forcing users to provide a specific format. You can do more and better for your customers!
static Validation::datetime(array $check, mixed $dateFormat = 'ymd', string $regex = null)
This rule ensures that the data is in a valid datetime format. You can pass a parameter (can be an array) that specifies the format of the date to be verified. This parameter can be one of the following:
‘dmy’ e.g. 27-12-2006 or 27-12-06 (the separator can be space, period, dash, slash)
‘mdy’ For example 12-27-2006 or 12-27-06 (the separator can be space, period, dash, slash)
‘ymd’ For example, 2006-12-27 or 06-12-27 (the separator can be space, period, dash, slash)
‘dMy’ respectively 27 December 2006 or 27 Dec 2006
‘Mdy’ e.g. December 27, 2006 or Dec 27, 2006 (comma is optional)
‘My’ e.g. (December 2006 or Dec 2006)
‘my’ For example 12/2006 or 12/06 (the separator can be space, period, dash, slash)
If this key is not provided, 'ymd' will be used by default:
1 public $validate = array(
2 'birthday' => array(
3 'rule' => array('datetime', 'dmy'),
4 'message' => 'Please enter a valid date and time.'
5 )
6 );
A custom regular expression can be specified by passing the second parameter. If this parameter is used, use this as the standard for validation.
Unlike date(), datetime() verifies date and time.
static Validation::decimal(integer $check, integer $places = null, string $regex = null)
This rule ensures that the data is valid numbers. You can pass a parameter that specifies the number of digits after the decimal point. If no parameters are passed, the data must be strictly floating point. If no number is found after the decimal point, the check will fail:
1 public $validate = array(
2 'price' => array(
3 'rule' => array('decimal', 2)
4 )
5 );
static Validation::email(string $check, boolean $deep = false, string $regex = null)
This rule verifies whether the data is a valid email address. Passing a logical value as its second argument, this rule will attempt to check if the host in the address is valid:
1 public $validate = array('email' => array('rule' => 'email'));
2
3 public $validate = array(
4 'email' => array(
5 'rule' => array('email', true),
6 'message' => 'Please supply a valid email address.'
7 )
8 );
static Validation::equalTo(mixed $check, mixed $compareTo)
This rule ensures that the data is of the same type and numerical value as the given value.
1 public $validate = array(
2 'food' => array(
3 'rule' => array('equalTo', 'cake'),
4 'message' => 'This value must be the string cake'
5 )
6 );
static Validation::extension(mixed $check, array $extensions = array('gif', 'jpeg', 'png', 'jpg'))
This rule checks whether the file extension is .jpg or .png. Allows passing multiple extensions as an array.
1 public $validate = array(
2 'image' => array(
3 'rule' => array('extension', array('gif', 'jpeg', 'png', 'jpg')),
4 'message' => 'Please supply a valid image.'
5 )
6 );
static Validation::fileSize($check, $operator = null, $size = null)
This rule allows detection of file length. You can use $operator to determine the type of comparison required. All operations supported by comparison() are also supported here. This method will automatically handle the array value from $_FILES by reading the tmp_name key (if $check is an array containing that key):
1 public $validate = array(
2 'image' => array(
3 'rule' => array('filesize', '<=', '1MB'),
4 'message' => 'Image must be less than 1MB'
5 )
6 );
New features in version 2.3: This method was added in version 2.3.
static Validation::inList(string $check, array $list)
This rule ensures that the value is in the given set. It requires an array of values. A column is considered valid if its value matches a value in the given array.
For example:
1 public $validate = array(
2 'function' => array(
3 'allowedChoice' => array(
4
5 'message' => 'Enter either Foo or Bar.'
6 )
7 )
8 );
static Validation::ip(string $check, string $type = 'both')
This rule ensures that a valid IPv4 or IPv6 address is submitted. Accepts arguments 'both' (default), 'IPv4' or 'IPv6'.
1 public $validate = array(
2 'clientip' => array(
3 'rule' => array('ip', 'IPv4'), // or 'IPv6' or 'both' (default)
4 'message' => 'Please supply a valid IP address.'
5 )
6 );
static Validation::isUnique
Column data must be unique and cannot be used by other rows.
1 public $validate = array(
2 'login' => array(
3 'rule' => 'isUnique',
4 'message' => 'This username has already been taken.'
5 )
6 );
static Validation::luhn(string|array $check, boolean $deep = false)
Luhn algorithm: verification algorithm for various identification codes. See http://en.wikipedia.org/wiki/Luhn_algorithm for more information.
static Validation::maxLength(string $check, integer $max)
This rule ensures that the data is within the maximum length.
1 public $validate = array(
2 'login' => array(
3 'rule' => array('maxLength', 15),
4 'message' => 'Usernames must be no larger than 15 characters long.'
5 )
6 );
The length here is the "number of bytes of string data". Be careful, when dealing with non-ASCII characters, the value may be greater than the number of characters.
static Validation::mimeType(mixed $check, array $mimeTypes)
2.2 new features.
This rule checks for a valid mimeType
1 public $validate = array(
2 'image' => array(
3 'rule' => array('mimeType', array('image/gif')),
4 'message' => 'Invalid mime type.'
5 ),
6 );
static Validation::minLength(string $check, integer $min)
This rule ensures that the data is no less than the minimum length.
1 public $validate = array(
2 'login' => array(
3 'rule' => array('minLength', 8),
4 'message' => 'Usernames must be at least 8 characters long.'
5 )
6 );
The length here is the "number of bytes of string data". Be careful, when dealing with non-ASCII characters, the value may be greater than the number of characters.
static Validation::money(string $check, string $symbolPosition = 'left')
This rule ensures that the value is a valid monetary amount.
The second parameter defines the position of the currency symbol (left/right).
1 public $validate = array(
2 'salary' => array(
3 'rule' => array('money', 'left'),
4 'message' => 'Please supply a valid monetary amount.'
5 )
6 );
static Validation::multiple(mixed $check, mixed $options = array())
This rule is used to validate multiple select input forms. Supported parameters are "in", "max" and "min".
1 public $validate = array(
2 'multiple' => array(
3 'rule' => array('multiple', array(
4 'in' => array('do', 'ray', 'me', 'fa', 'so', 'la', 'ti'),
5 'min' => 1,
6 'max' => 3
7 )),
8 'message' => 'Please select one, two or three options'
9 )
10 );
static Validation::notEmpty(mixed $check)
This rule ensures that the column is not empty.
1 public $validate = array(
2 'title' => array(
3 'rule' => 'notEmpty',
4 'message' => 'This field cannot be left blank'
5 )
6 );
Do not use this rule when validating multiple select inputs, as it will cause errors. Please use "multiple" instead.
static Validation::numeric(string $check)
Verify whether the passed data is a valid number.
1 public $validate = array(
2 'cars' => array(
3 'rule' => 'numeric',
4 'message' => 'Please supply the number of cars.'
5 )
6 );
static Validation::naturalNumber(mixed $check, boolean $allowZero = false)
2.2 new features.
This rule checks whether the passed data is a valid natural number. If $allowZero is set to true, 0 will also be an acceptable value.
1 public $validate = array(
2 'wheels' => array(
3 'rule' => 'naturalNumber',
4 'message' => 'Please supply the number of wheels.'
5 ),
6 'airbags' => array(
7 'rule' => array('naturalNumber', true),
8 'message' => 'Please supply the number of airbags.'
9 ),
10 );
static Validation::phone(mixed $check, string $regex = null, string $country = 'all')
Phone verification is for US phone numbers. If you want to validate non-US phone numbers, you can provide a regular expression as the second parameter to override the additional number format.
1 public $validate = array(
2 'phone' => array(
3 'rule' => array('phone', null, 'us')
4 )
5 );
static Validation::postal(mixed $check, string $regex = null, string $country = 'us')
Postal codes are for the United States, Canada, United Kingdom, Italy, Germany and Belgium. For other zip codes, a regex can be provided as the second argument.
1 public $validate = array(
2 'zipcode' => array(
3 'rule' => array('postal', null, 'us')
4 )
5 );
static Validation::range(string $check, integer $lower = null, integer $upper = null)
This rule ensures that the passed value is within the given range. If no range is provided, this rule checks and confirms that the passed value is a legal value for the current platform.
1 public $validate = array(
2 'number' => array(
3 'rule' => array('range', -1, 11),
4 'message' => 'Please enter a number between 0 and 10'
5 )
6 );
The above example will accept values greater than 0 (e.g. 0.01) and less than 10 (e.g. 9.99).
Annotations
The upper/lower limits of the range are not included.
static Validation::ssn(mixed $check, string $regex = null, string $country = null)
Ssn Verifies Social Security numbers for the United States, Denmark and the Netherlands. For other social security numbers, a regular expression needs to be provided.
1 public $validate = array(
2 'ssn' => array(
3 'rule' => array('ssn', null, 'us')
4 )
5 );
static Validation::time(string $check)
Time check determines whether the passed string is a valid time. There are two formats: 24-hour format (HH:MM) or am/pm format ([H]H:MM[a|p]m). Seconds are not allowed and seconds are not checked.
static Validation::uploadError(mixed $check)
2.2 new features.
This rule detects whether an error occurred during file upload.
1 public $validate = array(
2 'image' => array(
3 'rule' => 'uploadError',
4 'message' => 'Something went wrong with the upload.'
5 ),
6 );
static Validation::url(string $check, boolean $strict = false)
This rule checks whether the URL format is valid. Supports http(s), ftp(s), file, news and gopher protocols:
1 public $validate = array(
2 'website' => array(
3 'rule' => 'url'
4 )
5 );
To ensure that the protocol is url, you can enable strict mode, the example is as follows:
1 public $validate = array(
2 'website' => array(
3 'rule' => array('url', true)
4 )
5 );
static Validation::userDefined(mixed $check, object $object, string $method, array $args = null)
Run a user-defined validation.
static Validation::uuid(string $check)
Check whether the value is a valid uuid: http://tools.ietf.org/html/rfc4122
Localization verification
The phone() and postal() validation rules pass all country prefixes they don't know what to do with to other classes with the correct names. For example, if you live in the Netherlands, you can create a class like this:
1 class NlValidation {
2 public static function phone($check) {
3 // ...
4 }
5 public static function postal($check) {
6 // ...
7 }
8 }
This file can be placed in APP/Validation/ or App/PluginName/Validation/, but it must be imported with App::uses() before trying to use it. You can use the NLValidation class in the validation class as follows:
1 public $validate = array(
2 'phone_no' => array('rule' => array('phone', null, 'nl')),
3 'postal_code' => array('rule' => array('postal', null, 'nl')),
4 );
When the model data is validated, Validation will see the nl country code it cannot handle and try to delegate to NlValidation::postal(), using its return value as the validation pass/fail result. This approach allows you to create a class that handles localization subsets or localization groups. The usage of the independent verification method has not changed, its capabilities are passed through the addition of additional validators.
Tips
The localization plugin already contains some useful rules: https://github.com/cakephp/localized You are also free to contribute your own localization verification rules.
Verify data in controller
Although normally you only use the save method of the model, occasionally you want to just verify the data without saving it. For example, you may want to display some additional information to the user before actually saving the data to the database. The data verification at this time is slightly different from the verification when saving the data.
First, assign the data to the model:
1 $this->ModelName->set($this->request->data);
Then, use the model’s verification method to check whether the data is valid. If valid, return true, otherwise return false:
1 if ($this->ModelName->validates()) {
2 // Data valid logic
3 } else {
4 // Logic of invalid data
5 $errors = $this->ModelName->validationErrors;
6 }
It is advisable to validate the model using only a subset of the validation set specified in the model. For example, there is a User model with first_name, last_name, email, and password. Want to verify all four column rules when creating or editing a user. When the user logs in, only the email and passowrd rules are verified. This can be achieved by passing option data to specify the columns to be verified:
1 if ($this->User->validates(array('fieldList' => array('email', 'password')))) {
2 // valid
3 } else {
4 // Invalid
5}
The validation method calls the invalidFields method to fill the validationErrors attribute of the model. The invalidFields method also returns these data:
1 $errors = $this->ModelName->invalidFields(); // Contains validationErrors array
The validation error list will not be cleared during consecutive calls to invalidFields(). So if the validation is done inside a loop and you want to separate the error set, don't use invalidFields(). Instead use the validates() method and access the model's validationErrors property.
It is important to note that data must be assigned to the model before it is verified. This is different from the save method, which allows data to be passed as parameters. Also, remember that you don't have to call verify before calling save, because save will automatically verify the data before actually saving it.
To verify multiple models, use the following method:
1 if ($this->ModelName->saveAll($this->request->data, array('validate' => 'only'))) {
2 // Invalid www.2cto.com
3 } else {
4 // Valid
5}
If the data has been verified before saving, you can turn off verification to prevent repeated detection:
1 if ($this->ModelName->saveAll($this->request->data, array('validate' => false))) {
2 // No more verification when saving
3}
http://www.bkjia.com/PHPjc/477761.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/477761.htmlTechArticleData Validation Data validation is an important part of any application because it helps ensure that the model The data complies with the application's business rules. For example, you might want to make sure...