filter_var是在php5.2.0中开始提供的。详细说明见:
http://www.php.net/manual/zh/book.filter.php
先看看代码:
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
|
<?php
class
Utils {
/**
* 主要是调用filter_var_array验证,再扩充一个required字段来表示必填项。
* http://www.php.net/manual/zh/book.filter.php
* 注意: (可以不传,但不能传错)
* 1.先验证格式,有失败的抛异常。
* 2.未传的参数,有default的(不管是否required=1),则设置为default值。
* 示例:
* $filterArr = array(
* "pn" =>array(
* "required" => 1,
* "filter" => FILTER_VALIDATE_INT,
* "options" => array(
* "default" =>1,
* "min_range" =>1,
* )
* )
* )
*/
public
static
function
filter_param(
$paramArr
,
$filterArr
){
$res
= filter_var_array(
$paramArr
,
$filterArr
);
//参数不合法-flase, 没传参数-null
foreach
(
$res
as
$key
=>
$val
){
//如果有验证失败的,抛出异常。
if
(false ===
$val
){
throw
new
Exception(
"Utils::filter_param: failed, key=$key "
);
}
//再判断未传的参数。
if
(
is_null
(
$val
)){
//1.如果是必填项
if
(
$filterArr
[
$key
][
'required'
] ){
if
(isset(
$filterArr
[
$key
][
'options'
][
'default'
])){
//1.1如果有default值,则设置为default值。
$res
[
$key
] =
$filterArr
[
$key
][
'options'
][
'default'
];
}
else
{
//1.2如果没有default值,抛出异常。
throw
new
Exception(
"Utils::filter_param: Do not have required param, key=$key"
);
}
}
else
{
//$res[$key]=''; //这里是默认把null值改为空值。是否有必要?
}
}
}
return
$res
;
}
};
//每个model里,都写个checkParam函数,用来配置验证的规则。
function
checkParam(
$arrInput
){
//1.先检查catId
$filter
=
array
(
//数字类型的,必填。只允许 0-1。
"catId"
=>
array
(
"required"
=>1,
"filter"
=>FILTER_VALIDATE_INT,
"options"
=>
array
(
"min_range"
=>0,
"max_range"
=>1,
)
),
//字符串类型的,必填。长度大于1。
"title"
=>
array
(
"required"
=>1,
"filter"
=>FILTER_VALIDATE_REGEXP,
"options"
=>
array
(
"regexp"
=>
"/^.+/"
,
)
),
//字符串类型的,非必填。但要是填了的话,则格式必须为email。
"email"
=>
array
(
"filter"
=>FILTER_VALIDATE_EMAIL,
),
);
$_res
= Utils::filter_param(
$arrInput
,
$filter
) ;
}
//比如这个是输入的参数。可以试着修改这里看看效果。
$arrInput
=
array
(
'catId'
=>1,
'title'
=>
'xx'
,
'email'
=>
'xxxxxx.com'
,
);
try
{
$res
=checkParam(
$arrInput
);
echo
"验证通过,继续其它代码...\n"
;
}
catch
(Exception
$e
){
echo
'Caught exception: '
,
$e
->getMessage(),
"\n"
;
}
?>
|
上面的代码,可直接运行。
使用方法:
-
建议把filter_param放到公共函数库中。
-
建议在每个model里都有个checkParam函数,专门配置验证规则。
本文转自 xjtuhit 51CTO博客,原文链接:http://blog.51cto.com/51reboot/1427065