我正在尝试创建一个包含php过滤器的函数:
这样的事情:
function validate($data, $args, $errorMsg)
{
}
所以你可以验证这样的数据:
$data = array(
'product_id' => 'libgd<script>',
'component' => '10',
'versions' => '2.0.33',
'testscalar' => array('2', '23', '10', '12'),
'testarray' => '2',
);
$args = array(
'product_id' => FILTER_SANITIZE_ENCODED,
'component' => array('filter' => FILTER_VALIDATE_INT,
'flags' => FILTER_FORCE_ARRAY,
'options' => array('min_range' => 1, 'max_range' => 10)
),
'versions' => FILTER_SANITIZE_ENCODED,
'doesnotexist' => FILTER_VALIDATE_INT,
'testscalar' => array(
'filter' => FILTER_VALIDATE_INT,
'flags' => FILTER_REQUIRE_SCALAR,
),
'testarray' => array(
'filter' => FILTER_VALIDATE_INT,
'flags' => FILTER_FORCE_ARRAY,
)
);
但是,如果其中一个过滤器返回false,我也想显示错误消息,例如,如果组件返回false(例如,不是整数或超出范围),我想创建一个错误消息,例如“[field]不是整数“。怎么会这样做?
答案 0 :(得分:0)
您可以尝试抛出异常
http://www.php.net/manual/en/language.exceptions.php
如果validate()中存在错误,则使用此
时出错throw new Exception('[field] is not an integer');
所以验证将是
try(
Validate();
)
catch (Exception $e) {
echo 'Error: ', $e->getMessage(), "\n";
}