thinkphp Automatic Verification

Source: Internet
Author: User

Automatic verification of 1.thinkphp

  Automatic validation is a method of data validation provided by the Thinkphp model layer that automates data validation when creating data objects using create.


1.1 Scope of application:

Validation of data types, business rules, security judgments, and more.

1.2 Authentication method:      

1. Static mode: The validation rules are defined in the model class through the $_validate attribute.

2. Dynamic mode: Use the Validate method of the model class to dynamically create automatic validation rules.

1.3 Validation rules:

Example: Automatic verification of a simple registration information:

<?phpnamespace Home\model; UseThink\model;classUsermodelextendsmodel{protected $_validate=Array(                        Array(' Verify ', ' Require ', ' captcha must! ‘),//validation by default with regular                   Array(' name ', ' ', ' account name already exists! ', 0, ' unique ', 1),//Verify that the Name field is unique when added                   Array(' Value ',Array(a), ' The range of values is incorrect! ', 2, ' in '),//when the value is not empty, determine whether it is within a range                   Array(' Repassword ', ' Password ', ' Confirm password incorrect ', 0, ' confirm '),//Verify that the password is consistent with the password                   Array(' Password ', ' checkpwd ', ' Password format incorrect ', 0, ' function '),//Custom Function validation password format);
}

We use the above example to analyze the automatic validation rules for thinkphp:

Verify the format of the rule:

Array (          array(verify field 1, validation rule, error prompt, [validation condition, additional rule, validation time]),  
Array (Verify field 2, validation rules, error prompts, [validation conditions, additional rules, validation time]),
......
);

    Format Description:

validation field (required)

The name of the form field that needs to be validated, which is not necessarily a database field, or it can be a secondary field for a form, such as a confirmation password and verification code, and so on. Validation fields can be set arbitrarily if there are individual validation rules and field-independent conditions, such as expire expiration rules that are not related to form fields. If a field mapping is defined, the validation field name here should be the actual table field instead of the form field.

validation rules (required)

To validate the rules, you need to combine additional rules, if the use of regular validation of additional rules, the system also has built-in regular validation rules, can be used directly as a validation rule, including: Require field must, email mailbox, URL URL address, currency currency, Number.

prompt information (required)

Definition of the hint message for validation failure

    validation criteria (optional)

The following scenarios are included:

      • Self::exists_validate or 0 exists field is verified (default)
      • Self::must_validate or 1 must be verified
      • Self::value_validate or 2 value is not empty when validating
additional rules (optional)

Used with validation rules, including some of the following rules:

rules Description
Regex Regular validation, the defined validation rule is a regular expression (default)
function function validation, the defined validation rule is a function name
Callback Method validation, a defined validation rule is a method of the current model class
Confirm Verify that the two fields in the form are the same, and that the validation rule defined is a field name
Equal Verify that the value is equal to a value that is defined by the preceding validation rule
NotEqual Verify that the value is not equal to a value that is defined by the previous validation rule (new in the 3.1.2 version)
Inch Verifies whether a defined validation rule can be an array or a comma-delimited string within a range
Notin Verify that the validation rule defined is not within a range, either an array or a comma-delimited string (3.1.2 version added)
Length Validation length, the defined validation rule can be a number (representing a fixed length) or a range of numbers (for example, 3,12 indicates a range from 3 to 12)
Between Validation scopes, defined validation rules representing ranges, can use strings or arrays, such as 1,31 or array (1,31)
Notbetween Validation is not in a range, defined validation rules represent scope, can use strings or arrays (3.1.2 version added)
Expire Verify that the validation rules defined in the validity period represent a time range that can be used to time, for example, you can use 2012-1-15,2013-1-15 to indicate that the current commit is valid between 2012-1-15 and 2013-1-15, or you can use a timestamp definition
Ip_allow Verify that IP is allowed, the defined validation rules represent a list of allowed IP addresses, separated by commas, for example 201.12.2.5,201.12.2.6
Ip_deny Verify that IP is prohibited, the defined validation rules represent a list of forbidden IP addresses, separated by commas, for example 201.12.2.5,201.12.2.6
Unique Validation is unique, the system will query the database based on the current value of the field to determine if the same value exists, and when the form data contains a primary key field, unique cannot be used to determine the primary key field itself
verification Time (optional)
    • Self::model_insert or 1 new data when validating
    • Self::model_update or 2 edit data when validating
    • Self::model_both or 3 verification in all cases (default)

The verification time here needs to be noted, not only in these three cases, you can add additional validation time based on your business needs.

These are some of the parameters of automatic verification;

1.4 Calling automatic validation rules

  Once you have defined the validation rules, you can call them automatically when you create a data object using the Create method:

For the authentication rules of the registration information written above, the method is called:

$User // instantiating a User object if (! $User->create ()) {     //  If the creation failure indicates that validation did not pass the    output error message     exit( $User-GetError ());} Else {  //  validation can be done through other data operations }

  Statically defined mode because the model class must be defined, the automatic validation is written in modal, so we must use the D () method when we instantiate the object.

1.5 for forms not submitted by post method

  By default, the Create method automatically validates the post data submitted by the form, and if your data source is not a form post, it can still be verified automatically, as in the following ways:

$User // instantiating a User object $data // getting (array) data from a data source by using the GetData method if (! $User->create ($data)) {     //      validating data data     exit ($User,geterror ());} Else {     //  validation can be done through other data operations }

1.6 Dynamic Verification

If the dynamic authentication method, it is more flexible, according to different needs, in the operation of the same model when the use of different validation rules.

$rules=Array(     Array(' Verify ', ' Require ', ' captcha must! ‘),//By default, the array (' name ', ' ', ' account name already exists! ', 0, ' unique ', 1),//Verify that the Name field is unique when added Array(' Value ',Array(a), ' The range of values is incorrect! ', 2, ' in '),//when the value is not empty, determine whether it is within a range Array(' Repassword ', ' Password ', ' Confirm password incorrect ', 0, ' confirm '),//Verify that the password is consistent with the passwordArray(' Password ', ' checkpwd ', ' Password format incorrect ', 0, ' function '),//Custom Function validation password format);

$User= M ("User");//instantiating a User objectif(!$User->validate ($rules)->create ()) {//If the creation fails, the validation does not pass the output error message Exit($User-GetError ());}Else{ //Verify that other data operations can be performed by}

  Dynamic validation does not depend on the definition of a model class, so it is usually possible to instantiate the model with the M function.

   1.7 Batch Verification

  The system supports the batch verification function of data, only need to set the Patchvalidate property to true in model class (false by default)

protected $patchValidate true;

After you set up batch validation, the getError() error message returned by the method is an array, and the return format is:

Array ("Field Name 1" + = "Error 1", "field Name 2" = "error hint 2" ...)

    

    The front end can be handled on its own, as needed, such as converting to JSON format to return:

$User // instantiating a User object if (! $User->create ()) {     //  If the creation fails to indicate that the validation did not    pass the output error message     $this- Ajaxreturn ($User-geterror ());} Else {         //  validation can be done through other data operations }

    1.8 Custom Validation rules

Since we have some validation rules that do not meet our needs when customizing validation, we need to write some custom validation rules ourselves.

Cases:

Array // Custom Function validation password format);

     To verify the password, for example, the second parameter name of the validation rule must be the name of a function method:

function checkpwd () {    // PHP logic code for detecting passwords }

thinkphp Automatic Verification

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.