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'],
    ];
}

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);

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

Scene Reuse

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

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);

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
)

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'];
}

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

It is possible to define a method specifically for a certain scenario (the naming convention for the method is scene followed by the capitalized name of the scenario). The method provides a scenario class Itwmw\Validate\Support\ValidateScene which can be used to redefine the rules for certain fields, for example:

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');
}

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',
];

Validation scenario definition:

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

Methods of the Scene class

The following is an explanation of the scenario class methods for the validator:

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
removeCheckFieldRemove a field that does not require validation.
setEventPrioritySetting the priority of events and simple events
preprocessorSet up pre-data processing for specified fields.
postprocessorSet up post-data processing for specified fields.
nextSpecify the next scene or next scene selector

only

Specify the fields to be validated for the scenario

public function only(array $fields): $this
  • The $fields is an array of fields to be validated. When set to true, it means all fields will be validated. When set to false, it means no fields will be validated.

remove

Remove partial validation rules for fields in a scenario

public function remove(string $field, string $rule = null): $this
  • $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
  • $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
  • $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 Itwmw\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;
});

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
  • $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)

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

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
  • $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
  • $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
  • $field The name of the field to be added

removeCheckField

Remove a field that does not require 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
  • $field The name of the field to be deleted.

setEventPriority

Setting the priority of events and simple events

public function setEventPriority(bool $priority): $this
  • 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

preprocessor

Configure or unset a pre-processing data handler for a field.

public function preprocessor(string $field, callable|Closure|mixed|null|ProcessorInterface $callback, ProcessorSupport ...$params): static

Values, function names, the current class's processor method names, processor classes, closures, and so on can all be used as processors.

postprocessor

Configure or unset a post-processing data handler for a field.

public function postprocessor(string $field, callable|Closure|mixed|null|ProcessorInterface $callback, ProcessorSupport ...$params): static

next

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

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