Yii Learning Note IV (Form validation API translation)

Source: Internet
Author: User
Tags list of attributes valid email address yii

1. Form Validation
For all data entered by the user, you cannot trust it and must be verified.
All frameworks are so, for yii you can use functions
yii\base\model::validate () for verification
He will return a Boolean value of True/false
If validation does not pass, you can use the

Yii\base\model:: $errors property for processing, the following code:

<?php  //Load Form model (absolute address mode)/* If use App\models\contactform is introduced above    ;   You can directly use the   $model = new Contactform; */$model = new \app\models\contactform;//The field that receives the user-populated model is flipped into the property $model->attributes = \yii:: $app->request->post (' contactform '), if ($model->validate ()) {//    all input validation passed} else {    //validation failed: $ Errors is an array containing all the error messages    $errors = $model->errors;}? >

2. Claim Rules

To make the validation function validate () really work, we need to fix some validation
The rules correspond to these forms for validation, and he automatically overrides
yii\base\model::rules () method
The following example describes how to use the rules

<?phppublic function Rules () {    return [        //name, email, subject and body properties must be filled in        [[' Name ', ' email ', ' subject ', ' Body '], ' required ',        //email must be a valid email address        [' email ', ' email '], '    ;} The rule returns the format of the value [    //Required parameter one, which specifies that a property or some property of this rule must be observed.    For a single attribute, you can directly use the property name    //Do not have to put him in an array     [' attribute1 ', ' attribute2 ', ...],//For multiple then you can put in an array    //must be parameter two, Specifies the type of rule.    He can be a class name, an alias for a validation method, or a validation method name    ' Validator ',    //optional parameter three, specifying that scene using this rule    //if not given, means that all scenes of this rule will be applied    /  /You may also want to configure the "except" rule if you want to use this rule    //to all scenarios except the listed ones    ' on ' = = [' Scenario1 ', ' Scenario2 ', ...],    //optional parameters, custom additional configuration to the validation item    ' property1 ' = ' value1 ', ' property2 ' = ' value2 ', ...]? >

1> for each rule, you must specify at least which properties of the rule apply to what is the type of the rule. You can specify the type of rule in one of the following forms:

(1) The aliases of the core authentication, such as required, in, date, and so on. See the complete list of core validators as the core validator.

(2) The name of the validation method in the model class, or an anonymous function. Please refer to the inline validator for more information.

(3) A fully qualified validator class name. Please refer to the standard validator

A rule can be used for one or more property validations, and one property can be validated by one or more rules. Rules can in some cases
The app can only be specified by option. If you do not select Specify, this means that the rule will apply to all cases.

2> when the Validate () method is called, the following steps explain the validation process:

(1) First determine which attributes should be validated by obtaining a list of attributes
Yii\base\model::scenarios () uses the current scene. These properties are called active properties.

(2) Determine which validation rules will be used by getting the rule list from
yii\base\model::rules () is used in the current scene. These rules are called active rules.

(3) Use an active rule to verify each active attribute associated with the corresponding rule.
These validation rules are executed according to the order in which they are listed.

3. Customizing error messages

Most validations have default error messages that are displayed when validation fails. For example required validation can add a "Username cannot be blank." will appear automatically when the Username is not filled out, as follows:

<?phppublic function Rules () {    return [        ' username ', ' required ', ' message ' = ' Please choose a username '],    ];}? >

Some may verify that additional additional error messages are supported to more accurately describe the different reasons for the validation failure. For example, the digital validator supports TOOBIG and Toosmall to describe the values to validate when validation fails, respectively, too large, too small. You can configure these error messages just like other properties of a validation rule configuration validation.

4. Verifying Events

When yii\base\model::validate () is called, it will automatically invoke two custom methods:
Http://www.yiiframework.com/doc-2.0/yii-base-model.html#beforeValidate ()-detail

(1) yii\base\model::beforevalidate (): The default implementation automatically triggers a yii\base\model::event_before_validate event. You can also override this method or respond to this event by doing some preprocessing work (e.g. normalized data entry) before the validation event occurs. This method should return a Boolean value that indicates whether the validation should continue or not.

(2) yii\base\model::aftervalidate (): The default implementation automatically triggers a yii\base\model::event_after_validate Event. You can also override this method or respond to this event to do some processing after the validation is complete.

5. Conditional Validation

In order to verify that only certain conditions apply to the attribute, e.g. the validity of one property depends on the value of another property, which you can use when you define such a condition. For example, ' state ' is only established when ' model ' attribute value ' country ' is ' USA '

<?php[    [' state ', ' required ', ' when ' = function ($model) {        return $model->country = = ' USA ';    }],]? >

this when property carries a PHP call with the following signature:

<?php/** * @param model $model The model that is being validated @param string $attribute the property being validated * @return Boolean whether this validation succeeded */function ( $model, $attribute)

If you also want to support client condition validation, you should configure this whenclient property to pass in a string form
The JavaScript function code returns whether the rule is correct. For example,

[    ' state ', ' required ', ' when ' = function ($model) {        return $model->country = = ' USA ';    }, ' Whenclient ' = = "function (attribute, value) {        return $ (' #country '). val () = = ' USA ';    }"],

6. Data filtering

Data entered by the user is often preprocessed or filtered. For example, you might want to remove the spaces at both ends of username input.
You can use validation rules to achieve this effect.

The following example is to remove a space inputs convert the hole input box to nulls by using trim and default two core validators:

<?php[    [[' username ', ' email '], ' trim ',    [[' username ', ' email '], ' default '],]?>
you can show more general filtering to complete more complex data filtering.

As you can see, these validations do not validate the input. Instead, they return the input through the program to the authenticator.

7. Handling Empty Input

When the HTML forms form data is submitted, you usually need to assign some default values to these inputs if they are empty. You can do this, too. Use the default validation code like this:

<?php[    //Set "username" and "email" value null if not filled    [[' username ', ' email ', ' default '],    //set "level" to 1 if empty Words     [' level ', ' Default ', ' value ' = = 1],]?>

For the default validation, an input is considered empty if his value is an empty string, an empty array, or a null. You can customize the logic of this default value by configuring
The yii\validators\validator::isempty () property is called as a PHP call. For example:

<?php[    [' agree ', ' required ', ' isEmpty ' = function ($value) {        return empty ($value);    }],]?>

Tip: Most validations do not deal with empty inputs if their
The Yii\base\validator::skiponempty property takes the default True value. Just captcha, default, filter, required, and trim the validator handles the empty inputs.

8. Ad hoc Verification

Sometimes you need to do a special validation for some values that are not bound to any model

If you only need to perform one type of validation (e.g. verify email address), you can call the validate () method to find the appropriate validation,
Just like this:

<?php $email = ' [email protected] '; $validator = new Yii\validators\emailvalidator (); if ($validator->validate ($ Email, $error) {    echo ' email is valid. ';} else {    echo $error;}? >

Tip: Not all validators support this type of validation. An example is the unique core validation, which is designed to work with patterns only.

If you need to perform multiple validations on multiple values, you can use the
Yii\base\dynamicmodel can declare properties and rules at the same time. Use the following methods:

<?phppublic function Actionsearch ($name, $email) {    $model = Dynamicmodel::validatedata (the compact (' name ', ' email ' ), [[        ' [' [' Name ', ' email '], ' string ', ' max ' = +],        [' email ', ' email '],    ]);    if ($model->haserrors ()) {        //Validation failure code    } else {        //Validate Success Code    }}?>

This one
Yii\base\dynamicmodel::validatedata ()
Method creates an instance of Dynamicmodel that defines the properties using the given data (name and email in this example),
And then calls yii\base\model::validate () to carry the given rule.

Or you can use the "classic" syntax for the above validation:

<?phppublic function Actionsearch ($name, $email) {    $model = new Dynamicmodel (Compact (' name ', ' email '));    $model->addrule ([' Name ', ' email '], ' string ', [' max ' = +] ')        ->addrule (' email ', ' email ')        Validate ();    if ($model->haserrors ()) {        //Validation failure code    } else {        //Validate Success Code    }}?>

Yii Learning Note IV (Form validation API translation)

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.