ThinkPHP3.1 quick start (12) automatic verification

Source: Internet
Author: User
Tags form post
Automatic verification is a data verification method provided by the ThinkPHP model layer. you can perform automatic data verification when using create to create a data object. Automatic verification is a data verification method provided by the ThinkPHP model layer. you can perform automatic data verification when using create to create a data object.

Verification rules data verification allows you to verify data types, business rules, and security judgments.
There are two ways to verify data:
Static Mode: use the $ _ validate attribute to define verification rules in the model class.
Dynamic mode: Use the validate method of the model class to dynamically create automatic verification rules.
Regardless of the method, the Verification rule is defined as a unified rule in the following format:
  1. Array (
  2. Array (verification field 1, verification rules, error prompt, [verification conditions, additional rules, verification time]),
  3. Array (verification field 2, verification rules, error prompt, [verification conditions, additional rules, verification time]),
  4. ......
  5. );
Copy code Description
Verification field(Required) name of the form field to be verified. This field is not necessarily a database field, but can also be an auxiliary field of the form, such as confirming the password and verification code. If some verification rules have nothing to do with fields, the verification fields can be set at will. for example, the expire validity period rules are irrelevant to form fields. If field ING is defined, the verification field name here should be the actual data table field rather than the form field.
Verification rules(Mandatory) rules to be verified must be combined with additional rules. if you use additional rules for regular expression verification, the system also has built-in rules for common regular expression verification, it can be used directly as a verification rule, including: The require field is required, the email address, the url address, the currency of currency, and the number.
Prompt information(Required) defines the prompt information after verification fails.
Verification conditions(Optional) includes the following situations:
Model: EXISTS_VALIDATE or 0 (default)
Model: MUST_VALIDATE or 1 must be verified
Verification when Model: VALUE_VALIDATE or 2 is not null
Additional rules(Optional) use with verification rules, including the following rules:
Regex Regular expression verification. the defined validation rule is a regular expression (default)
Function Function verification. the defined verification rule is a function name.
Callback Method verification. the defined verification rule is a method of the current model class.
Confirm Verify that the two fields in the form are the same. The Validation rule is defined as a field name.
Equal Whether the verification is equal to a value, which is defined by the previous validation rule
Notequal Verify whether it is not equal to a value, which is defined by the preceding validation rules (3.1.2 added)
In Verify whether the validation rule is within a certain range. it can be an array or a comma-separated string.
Notin Verify whether it is not within a certain range. the defined validation rule can be an array or a comma-separated string (3.1.2 added)
Length Verification length. the defined verification rule can be a number (indicating a fixed length) or a number range (for example, 3, 12 indicates a length range from 3 to 12)
Between Verification range. the defined verification rules indicate the range. strings or arrays can be used, for example, 1, 31 or array (1, 31)
Notbetween Verification is not in a certain range. the defined verification rules indicate a range. you can use a string or an array (3.1.2 added)
Expire Whether the verification is in the validity period. The defined verification rules indicate the time range and the time range. for example, 2012-1-15, 2013-1-15 indicate that the current submission is valid between and, you can also use timestamp to define
Ip_allow Verify whether the IP address is allowed. the defined verification rules indicate the list of allowed IP addresses, which are separated by commas (,). For example, 201.12.2.5, 201.12.2.6
Ip_deny Verify whether the IP address is forbidden. the defined verification rules indicate the list of prohibited IP addresses, which are separated by commas (,). For example, 201.12.2.5, 201.12.2.6
Unique Verify that the database is unique. The system queries the database based on the current value of the field to determine whether the same value exists.
Verification time(Optional)
Model: MODEL_INSERT or 1 verification when adding data
Model: MODEL_UPDATE or 2 verification when editing data
Model: MODEL_BOTH or 3 verification in all cases (default)
The verification time here should be noted, not only these three cases, you can increase the verification time according to business needs.

Static definitions define the automatic verification rules of the model in advance in the model class.
For example, the $ _ validate attribute is defined in the model class as follows:
  1. Class UserModel extends Model {
  2. Protected $ _ validate = array (
  3. Array ('verify ', 'require', 'verification code is required! '), // Use regular expressions for verification by default
  4. Array ('name', '', 'account name already exists! ', 0, 'Unique', 1), // verify that the name field is unique when it is added.
  5. Array ('value', array (, 3), 'value range is incorrect! ', 2, 'in'), // determines whether the value is within the specified range when the value is not empty.
  6. Array ('repassword', 'password', 'confirm password is incorrect ', 0, 'confirm'), // verify that the password is consistent with the password
  7. Array ('password', 'checkpwd', 'incorrect password format', 0, 'Function'), // customize function verification password format
  8. );
  9. }
After you copy the code to define the verification rules, you can automatically call the create method to create a data object:
  1. $ User = D ("User"); // instantiate the User object
  2. If (! $ User-> create ()){
  3. // If creation fails, the verification fails and an error message is displayed.
  4. Exit ($ User-> getError ());
  5. } Else {
  6. // Other data operations can be performed after verification
  7. }
When the copied code performs automatic verification, the system will verify the defined verification rules in sequence. If a verification rule fails, an error is returned. the error message (string) returned by the getError method is the error message in the verification rule of the corresponding field.
By default, the create method automatically verifies the POST data submitted by the form. if your data source is not a form post, you can still perform automatic verification. the method is improved as follows:
  1. $ User = D ("User"); // instantiate the User object
  2. $ Data = getData (); // Get the (array) data of the data source using the getData method
  3. If (! $ User-> create ($ data )){
  4. // Verify data
  5. Exit ($ User-> getError ());
  6. } Else {
  7. // Other data operations can be performed after verification
  8. }
When you copy the code, the create method automatically determines whether to add new data or edit data (mainly to add primary key information through hidden data in the form ), you can also specify whether to add or edit the currently created data object, for example:
  1. $ User = D ("User"); // instantiate the User object
  2. If (! $ User-> create ($ _ POST, 1) {// specify new data
  3. // If creation fails, the verification fails and an error message is displayed.
  4. Exit ($ User-> getError ());
  5. } Else {
  6. // Other data operations can be performed after verification
  7. }
The second parameter of the Copy code create method is used to specify the verification time in the automatic verification rules. that is to say, the automatic verification of the create method only verifies the verification rules that match the verification time.
The verification time mentioned above is not only in these cases. you can increase the verification time according to your business needs. for example, you can specify a verification time of 4 for logon operations. We define the verification rules as follows:
  1. Class UserModel extends Model {
  2. Protected $ _ validate = array (
  3. Array ('verify ', 'require', 'verification code is required! '), // All have time for verification
  4. Array ('name', 'checkname', 'account error! ', 1, 'function', 4), // verification only at logon
  5. Array ('password', 'checkpwd', 'incorrect password! ', 1, 'function', 4), // verification only at logon
  6. );
  7. }
Copy the code so that we can use
  1. $ User = D ("User"); // instantiate the User object
  2. If (! $ User-> create ($ _ POST, 4) {// login verification data
  3. // Error message output when verification fails
  4. Exit ($ User-> getError ());
  5. } Else {
  6. // Verify that the logon operation is successful
  7. }
Copy code
Dynamic verification is more flexible if the dynamic verification method is used. you can use different verification rules when operating the same model according to different needs, for example, the above static verification method can be changed:
  1. $ Rules = array (
  2. Array ('verify ', 'require', 'verification code is required! '), // Use regular expressions for verification by default
  3. Array ('name', '', 'account name already exists! ', 0, 'Unique', 1), // verify that the name field is unique when it is added.
  4. Array ('value', array (, 3), 'value range is incorrect! ', 2, 'in'), // determines whether the value is within the specified range when the value is not empty.
  5. Array ('repassword', 'password', 'confirm password is incorrect ', 0, 'confirm'), // verify that the password is consistent with the password
  6. Array ('password', 'checkpwd', 'incorrect password format', 0, 'Function'), // customize function verification password format
  7. );
  8. $ User = M ("User"); // instantiate the User object
  9. If (! $ User-> validate ($ rules)-> create ()){
  10. // If creation fails, the verification fails and an error message is displayed.
  11. Exit ($ User-> getError ());
  12. } Else {
  13. // Other data operations can be performed after verification
  14. }
Copy code
Multi-language support for error messages if you want to support multi-language error message prompts, you can define the following in the verification rules:
  1. Protected $ _ validate = array (
  2. Array ('verify ', 'require', '{% VERIFY_CODE_MUST }'),
  3. Array ('name', '', '{% ACCOUNT_EXISTS}', 0, 'Unique', 1 ),
  4. );
Copy the code. VERIFY_CODE_MUST and ACCOUNT_EXISTS are the multilingual variables defined in the language pack.
If dynamic verification is used, it is relatively simple to use the L method when defining verification rules. for example:
  1. $ Rules = array (
  2. Array ('verify ', 'require', L ('verify _ CODE_MUST ')),
  3. Array ('name', '', L ('account _ exists'), 0, 'Unique', 1 ),
  4. );
Copy code
The batch verification system supports data batch verification. you only need to set the patchValidate attribute to true (the default value is false) in the model class ),
  1. Protected $ patchValidate = true;
After you copy the code to set the batch verification, the error message returned by the getError () method is an array and the returned format is:
  1. Array ("field name 1" => "error prompt 1", "Field name 2" => "error prompt 2 "...)
The front-end of the Copy code can handle it as needed, for example, convert the code to json format and return the result:
  1. $ User = D ("User"); // instantiate the User object
  2. If (! $ User-> create ()){
  3. // If creation fails, the verification fails and an error message is displayed.
  4. $ This-> ajaxReturn ($ User-> getError ());
  5. } Else {
  6. // Other data operations can be performed after verification
  7. }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.