39th Chapter thinkphp--Automatic Verification

Source: Internet
Author: User

In this lesson, we are going to learn a data validation method provided by the Thinkphp model layer that can be automatically validated when creating a data object using create.

A Validation rule data validation allows illegal validation of fields in a form.

Two types of authentication are generally available: static definition ($_validate property) and dynamic validation (Validate () method).

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

PS: Validation fields, validation rules, and error hints these three items are required, most of which are three, while validation conditions, additional rules, and validation times are optional. Validation field: Generally, the form's field name does not have to match the data table, because there are auxiliary fields such as password validation. Validation rules: The system has built-in common rules, require (field required), email (mailbox format), URL (url format), currency (currency), number (positive integer), Integer (integer), double (floating point), ZIP (postal code ), 中文版 (English). The additional rules that these rules take by default are regex, regular expression validation, just set. Error message: Prompt after validation failed.

Verification conditions: A total of three kinds:

1.self::exists_validate or 0, indicates that the field is present for validation (default);

2.self::must_validate or 1, indicating that it must be verified;

3.self::value_validate or 2, which indicates that the value is not empty when validating. Additional rules: Use with validation rules, including rules: Rule description Regex regular validation, defined validation rule is a regular expression (default) function validation, defined validation rule is a function name callback method validation, The validation rule defined is a method of the current model class confirm verify that the two fields in the form are the same, that the validation rule defined is a field name equal validation is equal to a value that is defined by the previous validation rule notequal Verify that it is not equal to a value. The value is defined by the previous validation rule (3.1.2 version) in to verify that a validation rule defined in a scope can be an array or a comma-delimited string notin Verify that the validation rule is not within a range, and that the defined authentication rules can be a Array or comma-separated string (new in 3.1.2 version) length Verify that the validation rule can be a number (representing a fixed length) or a range of numbers (for example, 3,12 represents a range from 3 to 12) between validation scope, defined validation rule representation range, You can use strings or arrays, such as 1,31 or array (1,31) Notbetween validation is not in a range, the defined validation rule represents the scope, you can use a string or array (3.1.2 version new) Expire verify whether the validity period, A defined validation rule represents a time range, which can be time-enabled, 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 to define Ip_allow to verify that the IP is allowed. A defined validation rule represents a list of allowed IP addresses, separated by commas, such as 201.12.2.5,201.12.2.6 Ip_deny to verify that IP is prohibited, a defined validation rule that represents a list of banned IP addresses, separated by commas, such as 201.12.2.5, 201.12.2.6 unique authentication is unique, the system will query the database based on the current value of the field to determine whether the same value exists, when the form data contains the primary key field, the unique is not used to determine the primary key field itself validation time: the main new modifications and other validation. 1.self::model_insert or 1 when new data is validated; 2.self::model_update or 2 is validated when editing data; 3.self::model_both or 3 is verified in all cases (default). Two Static fixedThe automatic validation rule of the model is defined in the model class, which is static definition. Model class definition validation rules class Usermodel extends model {protected $_validate = array (//By default with the system built-in array (' User ', ' require ', ' users must not be empty! '),//Verify data uniqueness of array (' User ', ' ', ' username already exists! ', 2, ' unique ', 1),//Verify that the password must not be an empty array (' pass ', ' require ', ' password must not be empty! '),//password must not be less than six bits not greater than 20 bit array (' pass ', ' 6,20 ', ' password must not be less than 6 bits, not greater than 20 bits ', 3, ' length '),); For testing convenience, we can submit the POST directly via the simulation://Controller Create () method to automatically invoke the verification $user = D (' user '); $data [' user '] = ' crayon small new '; $data [' pass '] = ' 123 '; if ($user->create ($data)) {echo ' All data verified successfully! ‘; } else {//Output error message Var_dump ($user->geterror ());} Thinkphp provides nine types of automatic verification built-in scenarios, as follows://built-in authentication require, must not be empty usage array (' user ', ' require ', ' users must not be empty! '),//built-in verification email, legal mailbox Format array (' User ', ' email ', ' email ' format is not legal! '),//built-in authentication url, verify URL is legitimate array (' user ', ' url ', ' URL path is not legal! '),//built-in verification currency, verify whether the currency array (' User ', ' currency ', ' currency format is incorrect! '),//built-in verification zip, verify that the six-bit integer zip code array (' user ', ' zip ', ' postal code format is incorrect! ‘),

//built-in verification number, verify that the positive integer array (' user ', number, ' positive integer ' is not properly formatted!) '),//built-in verification integer, verify whether it is an integer, plus or minus can be array (' User ', ' integer ', ' integer ' Format is incorrect! '),//built-in authentication double, verify whether it is a floating-point number, plus or minus can be array (' user ', ' Double ', ' integer format is incorrect! '),//built-in verification 中文版, authentication is a plain English array (' user ', ' 中文版 ', ' not plain English! '), thinkphp also provides additional rules to enhance the extensibility of automatic Validation://Additional rules regex, verifying 3-6-bit pure digit array (' user ', '/^\d{3,6}$/', ' not 3-6-bit pure number ', 0, ' regex '),//Additional rules Equal, verifies whether and the specified values are equal to the array (' user ', ' Li Tinghui ', ' value not equal ', 0, ' equal '),//Additional rules notequal, verifies whether the array (' user ', ' Li Tinghui ', ' value cannot equals ' is unequal to the specified value), 0, ' No Tequal '),//Add rule confirm, verify that two fields are the same as array (' user ', ' name ', ' two ' username is different! ', 0, ' confirm '),

//Additional rule in, a range, can be an array or comma-separated string array (' user ', array (+/-), ' not specified range ', 0, ' in '), array (' User ', ' Zhang San, John Doe, Harry ', ' not specified range ', 0, ' In '),//Additional rule notin, a range, can be an array or comma-separated string array (' user ', array (all-in-one), ' must not be in the specified range ', 0, ' notin '), array (' User ', ' Zhang San, John Doe, Harry ', ' Must not be in the specified range ', 0, ' notin '),//Additional rule length, verify length or number range of array (' User ', ' 3 ', ' must not be less than 3 bits ', 0, ' length '), array (' User ', ' 3,5 ', ' must not be less than 3 bits, Must not be greater than 5 bits ', 0, ' length '),//additional rule between, verify a range, number or comma string array (' user ', array (3,5), ' must be 3-5 number ', 0, ' between '), Array (' US Er ', ' 3,5 ', ' must be a number between 3-5 ', 0, ' between '),//Additional rule notbetween, verify a range, number or comma string array (' user ', array (3,5), ' must not be 3-5 digits ', 0 , ' Notbetween '), array (' User ', ' 3,5 ', ' must not be 3-5 between the number ', 0, ' notbetween '),//Additional rules expire, set the validity range, must be a form submission valid, can be a timestamp array (' User ', ' 2014-1-10,2015-10-10 ', ' time expired ', 0, ' expire '),//Additional Rules Ip_deny,ip Forbidden List Array (' User ', ' 127.0.0.1 ', ' when money IP is forbidden ', 0, ' Ip_ Deny '),//Additional rules IP_ALLOW,IP allow list array (' User ', ' 127.0.0.1 ', ' current IP not allowed ', 0, ' Ip_allow '),

Additional rule callback, callback authentication array (' User ', ' checklength ', ' username must be in 3-5 bits ', 0, ' callback ', 3, Array (3,5)),

callback method protected function Checklength ($STR, $min, $max) {Preg_match_all ("/./", $str, $matches); $len = count ($matches [0]) ; if ($len < $min | | $len > $max) {return false;} else {return true;}} Additional rule functions, function validation Array (' user ', ' checklength ', ' username must be in 3-5 bits ', 0, ' function ', 3, Array (3,5)),//Common file under Common folder The clip establishes the function.php file, which automatically loads function checklength ($str, $min, $max) {Preg_match_all ("/./", $str, $matches); $len = count ($mat Ches[0]); if ($len < $min | | $len > $max) {return false;} else {return true;}} If there are multiple fields that contain errors, only one error is displayed by default. If you want to display all errors, you can set the properties://Batch Verify protected $patchValidate = true; If the direct POST comes, use the Create () method directly.

The controller create () method automatically calls validation $user = D (' user '); if ($user->create ()) {echo ' All data verified successfully! ‘; } else {//Output error message Var_dump ($user->geterror ());}

PS: Because of the Usermodel model class used, the D () method must be instantiated.

If you want to return the error message to AJAX processing, you can return the JSON data with the Ajaxreturn () method.

Returns the JSON format $this->ajaxreturn ($user->geterror ());

1 Specify new data validation, 2 for modification, if ($user->create ($_post,1)) {}

Three is usually determined automatically. Dynamic verification dynamic verification is to put the rules of validation on the controller side, so that in the operation of the time is more flexible, the disadvantage is more chaotic.

Dynamic Authentication $rule = Array (' user ', ' require ', ' username must not be null '); $user = M (' user '); $data [' user '] = '; if ($user->validate ($rule)->create ($data)) {echo ' Validates all fields successfully! ‘; } else {var_dump ($user->geterror ());}

39th Chapter 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.