Yii2 验证一个空数组(空数组)
Yii2 Validating an empty array (null array)
我有这种情况,我有如下表格:
public $selling_price;
public $numbers;
public $inventory_factor;
public function rules() {
return [
['selling_price'], 'integer'],
[['inventory_factor'], 'safe'],
['numbers', 'each', 'rule' => ['integer']],
}
我有这个最后的验证规则来确保我得到一个整数数组。例如,当输入是一个字符串时,这很好用。如果发送数组 [null],IT 将不起作用。例如,这不会引发错误
{
"selling_price": 2200,
"numbers": [null]
}
使用 vardumper,将数字数组设为
[
0 => null
]
在 Yii2 中有没有什么方法可以在开始之前从数组中删除(过滤)空值,或者也可以验证这些空值?
['numbers', 'integer', 'min' => 0]
这将验证该值是否为大于 0 的整数(如果它不为空)。普通验证器将 $skipOnEmpty 设置为 true。
参考:https://www.yiiframework.com/doc/guide/2.0/en/input-validation
在这个数据过滤主题中你可以参考这些
查看核心验证器的专题后,我看到在 each 验证器下它显示:
rule: an array specifying a validation rule. The first element in the array specifies the class name or the alias of the validator. The rest of the name-value pairs in the array are used to configure the validator object.
此外,对于扩展 yii\validators\Validator 的 yii\validators\EachValidator,它有一个 属性 $skipOnEmpty
,默认为 true
:
$skipOnEmpty public property
- Whether this validation rule should be skipped if the attribute value is null or an empty string.
public boolean $skipOnEmpty = true
因此,相应地,您需要按如下方式调整规则。
['numbers', 'each', 'rule' => ['integer', 'skipOnEmpty' => false]],
现在 numbers
的验证器不会对数组中的空值视而不见 - 如果它发现任何空值或非整数值,验证将失败。
我有这种情况,我有如下表格:
public $selling_price;
public $numbers;
public $inventory_factor;
public function rules() {
return [
['selling_price'], 'integer'],
[['inventory_factor'], 'safe'],
['numbers', 'each', 'rule' => ['integer']],
}
我有这个最后的验证规则来确保我得到一个整数数组。例如,当输入是一个字符串时,这很好用。如果发送数组 [null],IT 将不起作用。例如,这不会引发错误
{
"selling_price": 2200,
"numbers": [null]
}
使用 vardumper,将数字数组设为
[
0 => null
]
在 Yii2 中有没有什么方法可以在开始之前从数组中删除(过滤)空值,或者也可以验证这些空值?
['numbers', 'integer', 'min' => 0]
这将验证该值是否为大于 0 的整数(如果它不为空)。普通验证器将 $skipOnEmpty 设置为 true。
参考:https://www.yiiframework.com/doc/guide/2.0/en/input-validation
在这个数据过滤主题中你可以参考这些
查看核心验证器的专题后,我看到在 each 验证器下它显示:
rule: an array specifying a validation rule. The first element in the array specifies the class name or the alias of the validator. The rest of the name-value pairs in the array are used to configure the validator object.
此外,对于扩展 yii\validators\Validator 的 yii\validators\EachValidator,它有一个 属性 $skipOnEmpty
,默认为 true
:
$skipOnEmpty public property - Whether this validation rule should be skipped if the attribute value is null or an empty string.
public boolean $skipOnEmpty = true
因此,相应地,您需要按如下方式调整规则。
['numbers', 'each', 'rule' => ['integer', 'skipOnEmpty' => false]],
现在 numbers
的验证器不会对数组中的空值视而不见 - 如果它发现任何空值或非整数值,验证将失败。