Validate Scene

Both the rule manager and the validator support defining scenarios and validating data for different scenarios. For example:

class ArticleValidate extends Validate
{
    protected $rule = [
        'id'      => 'required|numeric',
        'content' => 'required|digits_between:1,2000',
        'title'   => 'required|digits_between:4,50|alpha',
    ];

    protected $message = [
        'id.required'            => 'Missing parameter: Article Id',
        'id.numeric'             => 'Parameter error: Article Id',
        'content.required'       => 'The content of the article must be filled in',
        'content.digits_between' => 'Article length is 1~2000 characters',
        'title.required'         => 'The title of the article is required',
        'title.digits_between'   => 'Wrong article title format',
        'title.alpha'            => 'Article title length is 4~50 characters',
    ];
    
    protected $scene = [
        'add'  => ['content','title'],
        'edit' => ['id','content','title'],
        'del'  => ['id'],
    ];
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

Then you can use the validation scenario in the validation method, using the scene method to specify the validation scenario

$data = [
    'content' => 'some content',
    'title'   => 'This is a title'
];
$validate = new ArticleValidate();
$data     = $validate->scene('add')->check($data);
1
2
3
4
5
6

Validate scene reuse and association

You can use the next keyword to use the validator if both validation scenarios have the same field requirements or if you want to specify that you want to continue validating the next scenario after the current one

Note

Rule Manager does not support next keyword

Scene Reuse

protected $scene = [
    'edit' => ['id','content','title'],
    'save' => ['next' => 'edit'],
];
1
2
3
4
$validate = new ArticleValidate();
$validate->scene('save')->check($data);
1
2

Here is the save scenario, which actually uses the edit scenario field

If both middleware is defined, both are valid

Scene association

When we want some fields to meet the requirements and then continue to validate others, or a free combination of scenarios, we need to use the scenario association.

class User extends Validate
{
    protected $rule = [
        'username' => 'required|alpha',
        'password' => 'required|alpha_num|min:6|max:16',
        'mobile'   => 'regex:/^1[3-9]\d{9}$/',
        'name'     => 'alpha|max:10',
        'age'      => 'numeric|min:1|max:150'
    ];

    protected $scene = [
        'register'      => ['username', 'password', 'mobile', 'next' => 'checkUserInfo'],
        'checkUserInfo' => ['name', 'age']
    ];
}

$data = User::make()->scene('register')->check([
    'username' => 'Melody',
    'password' => '123456',
    'mobile'   => '13122223333',
    'name'     => 'Melody',
    'age'      => '20'
]);

print_r($data);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

The above code will first verify the register scene, and if all the fields in register pass the verification, continue to verify the checkUserInfo scene, and finally get all the data that pass the verification

Array
(
    [username] => Melody
    [password] => 123456
    [mobile] => 13122223333
    [name] => Melody
    [age] => 20
)
1
2
3
4
5
6
7
8

Scene selector

The next keyword supports the use of scene selectors. The naming convention for scene selectors is: scene selector name + Selector.

protected $scene = [
    'save' => ['type','next' = 'saveType'],
    'saveSetting' => ['id','name']
]


protected function saveTypeSelector(array $data)
{
    return 'save'.$data['type'];
}
1
2
3
4
5
6
7
8
9
10

Parameters of custom methods

The custom method will have an array type parameter, the incoming parameter is all the data previously verified, the return string is using the corresponding validation scene, and the return array is using the corresponding validation field

Custom validate scene

Methods can be defined separately for a scene (the naming convention for methods is scene + Initial capitalization of the scene name), and the rules for certain fields can be reset. For example:

  • The scene class in the rule manager is:W7\Validate\Support\RuleManagerScene
  • The scene class in the validator is: W7\Validate\Support\ValidateScene

Note

Scene names cannot be called with the hump writing converted to underscore

protected function sceneEdit($scene)
{
    return $scene->only(['id','content','title'])
        ->append('id',"max")
        ->remove("content",'between')
        ->remove('title',null)
        ->append('title','required|between|alpha');
}
1
2
3
4
5
6
7
8

TIP

The scene validation scenario will be reset after the check method is called and will not take effect for the next check.

Validate fields as arrays

In the validator, rules are supported for defining the elements under the array, and in the validation scenario, the same support is given for specifying the validation array elements

The rules are defined as follows:

protected $rule = [
    'search.order'   => 'numeric|between:1,2',
    'search.keyword' => 'chsAlphaNum',
    'search.recycle' => 'boolean',
];
1
2
3
4
5

Validation scenario definition:

protected $scene = [
    'list'    =>  ['search.order','search.keyword','search.recycle']
];
1
2
3

Methods of the Scene class

The Scene class methods of the validator are described as follows:

Method nameDescription
onlyFields to be validated in the scene
removeRemove partial validation rules for fields in a scenario
appendAppend validation rules to the fields in the scenario
sometimesComplex conditional validation
eventSpecifying event handling classes
getDataGet the current validation data
getValidateDataSame effect as getData,The difference is that this method returns a validator collection class
beforeAdd a method that needs to be executed before validation
afterAdd a method that needs to be executed after validation
appendCheckFieldAdd a field that needs to be validated
removeCheckFieldDelete a field that requires validation
setEventPrioritySetting the priority of events and simple events
defaultSet or remove the default value of a field
filterSet or unset filters for a field
nextSpecify the next scene or next scene selector

The Scene class methods of the Rule Manager are described as follows:

Method nameDescription
onlyFields to be validated in the scene
removeRemove partial validation rules for fields in a scenario
appendAppend validation rules to the fields in the scenario
appendCheckFieldAdd a field that needs to be validated
removeCheckFieldDelete a field that requires validation

only

Specify the fields to be validated for the scenario

public function only(array $fields): $this
1
  • $fields is the array of fields to be validated

remove

Remove partial validation rules for fields in a scenario

public function remove(string $field, string $rule = null): $this
1
  • $field is the field to be removed from the rule
  • $rule is the rule to be removed, multiple rules are split by |.you can also fill in an array of rules. If $rule is null, all rules under this field will be cleared.

append

Append validation rules to the fields in the scenario

public function append(string $field, string|array|Closure $rule): $this
1
  • $field is the field to append the rule to
  • $rule is the rule to be appended, multiple rules are split by |, and can also be filled into an array of rules,or closure rules, the format of closures is the same as extend

sometimes

Complex Conditional Validation

Sometimes you may wish to add validation rules based on more complex conditional logic. For example, you may wish to require a given field only if another field has a greater value than 100. Or, you may need two fields to have a given value only when another field is present.

public function sometimes($attribute, $rules, callable $callback): $this
1
  • $attribute To append the fields of a rule, multiple rules can use arrays.
  • $rules Rules to append, with multiple rules split by |. Arrays of rules can also be used.
  • $callback Closure method, if it returns true, the rules will be added

Parameters

The $input parameter passed to your Closure will be an instance of W7\Validate\Support\Storage\ValidateCollection and may be used to access your input and files.

This method makes it a breeze to build complex conditional validations. You may even add conditional validations for several fields at once.

$scene->sometimes(['name','sex'],'required',function ($data) {
    return $data->type === 1;
});
1
2
3

event

Specify the scene event handler class. Multiple scene event handler classes can be used for a scene

public function event(string $handler, ...$params): $this
1
  • $handler Processor namespace, can be passed in using :class
  • $params Parameters passed to the middleware build method,Unlimited number

getData

Get the current validation data

public function getData(string $key = '', $default = null)
1

Get all validated values by default

getValidateData

Get the current validation data. Same effect as getData,The difference is that this method returns a validator collection

public function getValidateData(): ValidateCollection
1

before

Add a method that needs to be executed before validation, the method is limited to methods of this class. The method naming rule is before plus the method name, and the method definition is viewed as Simple use.

public function before(string $callbackName, ...$params): $this
1
  • $callbackName The method name of this class, without prefix
  • $params The parameters to be passed to the method

after

Add a method that needs to be executed after validation, the method is limited to methods of this class. The method naming rule is after plus the method name, and the method definition is viewed as Simple use.

public function after(string $callbackName, ...$params): $this
1
  • $callbackName The method name of this class, without prefix
  • $params The parameters to be passed to the method

appendCheckField

Add a field that needs to be validated.

When you need to add a field that needs to be validated based on Sql or various other conditions, you need to use the appendCheckField method.

public function appendCheckField(string $field): $this
1
  • $field The name of the field to be added

removeCheckField

Delete a field that requires validation.

When you need to remove a field that is being validated based on Sql or various other conditions, you need to use the removeCheckField method.

public function removeCheckField(string $field): $this
1
  • $field The name of the field to be deleted.

setEventPriority

Setting the priority of events and simple events

public function setEventPriority(bool $priority): $this
1
  • When True, the order of execution is:Event class beforeValidate->Simple Events before->Start data validation->Simple Events after->Event class afterValidate
  • When False, the order of execution is:Simple Events before->Event class beforeValidate->Start data validation->Event class afterValidate->Simple Events after

default

Set or remove the default value of a field

public function default(string $field, $callback, bool $any = false): $this
1
  • $field Name of the data field to be processed
  • $callback The default value or an anonymous function that returns the default value which will,If this parameter is null, the default value of the field will be removed
  • $any Whether to handle arbitrary values, default only handle values that are not null

filter

Set or unset filters for a field

public function filter(string $field, $callback): $this
1
  • $field Name of the data field to be processed
  • $callback The filter. This can be a global function name,filter class, anonymous function, etc.

next

public function next(string $name): $this
1
  • $name Next scene or next scene selector

Use the instructions for reference:[Scene reuse and association](Scene.md#Validate scene reuse and association)

Last Updated: 9/13/2021, 7:27:21 PM