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
Note
Rule Manager does not support next
keyword
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
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
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');
}
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 Scene class methods of the validator are described as follows:
Method name | Description |
---|---|
only | Fields to be validated in the scene |
remove | Remove partial validation rules for fields in a scenario |
append | Append validation rules to the fields in the scenario |
sometimes | Complex conditional validation |
event | Specifying event handling classes |
getData | Get the current validation data |
getValidateData | Same effect as getData,The difference is that this method returns a validator collection class |
before | Add a method that needs to be executed before validation |
after | Add a method that needs to be executed after validation |
appendCheckField | Add a field that needs to be validated |
removeCheckField | Remove a field that does not require validation. |
setEventPriority | Setting the priority of events and simple events |
default | Set or remove the default value of a field |
filter | Set or unset filters for a field |
next | Specify the next scene or next scene selector |
The Scene class methods of the Rule Manager are described as follows:
Method name | Description |
---|---|
only | Fields to be validated in the scene |
remove | Remove partial validation rules for fields in a scenario |
append | Append validation rules to the fields in the scenario |
appendCheckField | Add a field that needs to be validated |
removeCheckField | Remove a field that does not require validation. |
only
Specify the fields to be validated for the scenario
public function only(array $fields): $this
$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
$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
isnull
, 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 returnstrue
, 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;
});
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
default
Set or remove the default value of a field
public function default(string $field, $callback, bool $any = false): $this
$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
$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
$name
Next scene or next scene selector
Use the instructions for reference:[Scene reuse and association](Scene.md#Validate scene reuse and association)