Automatic validation of the Create () method in thinkphp

Source: Internet
Author: User

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

Principle:

The Create () method collects the form ($_post) information and returns it, while the contact sheet automatically validates, filters the illegal fields,

Using the Create () method in the controller (the return value is True/false), the $_validate attribute in the model class is automatically triggered (overridden in the subclass model for the method in the parent class model), in $_ The custom validation rule in validate (explained in detail below the validation rule), when the Create () method has no data that returns a value of False,->geterror () by $xxx object, gets and returns an error message!

Using automatic validation must be defined in the following rule format:

protected $_validate = array (         array(validation field 1, validation rule, error prompt, [validation condition, additional rule, validation time]),     array(validation field 2, validation rule, error prompt, [validation criteria, additional rules , verify time]),     ... );    

Where validation fields, validation rules, error prompts are required, validation conditions, additional rules, validation time is optional!

validation field (required): form fields.

Validation Rule (required): Require field must, email mailbox, url URL address, number numbers, can also be used in conjunction with additional rules.

Error prompt (required): The prompt that is returned when validation fails.

Validation criteria (optional): There are 0,1,2 three kinds, field validation exists in 0:_post, default; 1: Validation rules are defined and must be validated; 2: value is not NULL when validating.

Additional rules:

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): Total 1, 2, 33, 1: Validate when new data is added, 2: Validate when editing data, 3: Validate in all cases (default), or add additional validation time to your business needs

The following code is attached: register as an example

The front page is relatively simple, the code is not posted out, the following is the front desk registration interface

Controller code:

//Register     Public functionRegister () {$user=New\model\usermodel (); //Two logic: collection, Presentation      if(!Empty($_post)) {                //the Create () method collects the form ($_post) information and returns it, while the contact sheet automatically verifies that the illegal field is filtered        $date = $user Create (); //The return value of the Create () method is used to determine whether the validation was successful        if($date) {//add//implode () to return the actual data to the string          $date[' user_hobby '] =implode(‘,‘,$date[' User_hobby ']);  $info = $user->add ($date);           if($info) {                        //Jump Home            $this->redirect (' Index/index '); }        }Else{          //assigning error messages to the foreground template           $error = $user-GetError ();           $this->assign (' Error ',$error); }      }       //call The View view      $this-display (); }

Model Class Code:

classUsermodelextendsmodel{//whether to batch process validation, bulk get all the error verification information    protected $patchValidate=true;//false By default//auto-Validate definition    protected $_validate=Array(        //Array (field, validation rule, error prompt, validation condition, additional rule, validation time)//① user name verification, cannot be empty        Array(' username ', ' require ', ' user name cannot be null '),Array(' username ', ', ' the user name is already occupied ', ' 0 ', ' unique '),//② password Authentication, not empty        Array(' Password ', ' Require ', ' password cannot be empty '),//③ Verification Confirmation password, must fill in, and password consistent        Array(' Password2 ', ' Require ', ' Confirm password must be filled in '),Array(' Password2 ', ' password ', ' two times password consistent ', 0, ' confirm '),//④ Mailbox Verification        Array(' User_email ', ' email ', ' email ' is not properly formatted ', 2),//⑤QQ Verification, number composition, 5-12-bit        Array(' user_qq ', ' number ', ' QQ must be Digital '),Array(' User_qq ', ' 5,12 ', ' digits between 5-12 bits ', 0, ' length '),//⑥ Qualification Verification, must choose a        Array(' User_xueli ', ' 2,5 ', ' degrees must be chosen ', ' 0, ' between '),//⑦ Hobby Verification, must choose more than two//because the hobby returns an array, there are no rules that can be used directly in the additional rules, so you need to customize the method and validate it with the callback method .        Array(' User_hobby ', 'Check_hobby', ' hobby must choose two or more ', 1, ' callback '),        ); //define methods for hobby verification//parameter $arg represents the validated form information    function Check_hobby($arg)    {        //determine if the array length is greater than 2        if(Count($arg) <2) {            return false;//The validation error message is automatically output        }        return true; }}

Display the validation error message in the template (part of the code)

<TD style= "width:13%; Text-align:right; " >
for class= "Required" > user name <span>*</span></label>
</TD><TD style= "width:87%;" > class= "INPUTBG" size= "name=" username "id=" user_username "type=" text "value=" "/> < Span style= "color:red;" ><{$error. Username|default: ""}></span></td>

Results:

Automatic validation of the Create () method in thinkphp

Related Article

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.