首頁 >php教程 >php手册 >自己写一个验证Validate类,希望对大家开发有帮助

自己写一个验证Validate类,希望对大家开发有帮助

WBOY
WBOY原創
2016-06-07 11:41:381867瀏覽

相信大家也用过thinkphp model 中的验证,也蛮好用的,自己在用前端js 验证类时感觉很多不错,自己就照着它的模式写了一个验证类,希望同学们喜欢
类中已经写好调用实例

示例1:普通调用
* $u_validate = Validate::model();
* //需要验证的数据
$data = array("name2"=>"0","name4"=>"admin173.com");
* //验证规则
$rules = array(
array('name'=>"name2","func"=>"min","params"=>1,"options"=>array('erroron'=>false)),
array('name'=>"name4","func"=>"email","params"=>1)
);
* //执行验证
$rtn = $u_validate->check($data, $rules);
if ($rtn === false) {
echo $u_validate->getError();
}
*
* 示例2:二维数组调用
* $u_validate = Validate::model();
$data = array(
array("name2"=>"1","name4"=>"admin173.com"),
array("name2"=>"中文sdfdsf","name4"=>"admin173.com")
);

$rules = array(
array('name'=>"name2","func"=>"min","params"=>1,"options"=>array('erroron'=>false)),
array('name'=>"name4","func"=>"email","params"=>1)
);

$rtn = $u_validate->check($data, $rules);

* 示例3:自定义错误消息
* $data = array("name2"=>"0","name4"=>"admin173.com");
* $u_validate = Validate::model();
* $rules = array(
array('name'=>"name2","func"=>"min","params"=>1,'msg'=>'最小值',"options"=>array('erroron'=>false)),
array('name'=>"name4","func"=>"email","params"=>1)
);
*
* $rtn = $u_validate->check($data, $rules);
*
* 示例4:调用其他验证方法
* $u_validate = new Validate();
$data = array(
array("name2"=>"1","name4"=>"admin173.com"),
array("name2"=>"中文sdfdsf","name4"=>"admin173.com")
);

$rules = array(
array('name'=>"name2","func"=>array(array(new Core(),'check')),"params"=>array(2,3),"options"=>array('erroron'=>false)),
);

$rtn = $u_validate->check($data, $rules);
if ($rtn === false) {
echo $u_validate->getError();
}
*
* 示例4:添加验证方法
$u_validate = Validate::model();
$data = array(
array("name2"=>"2","name4"=>"admin173.com"),
);

$rules = array(
array('name'=>"name2","func"=>array('checkname'),"params"=>3),
);
//添加验证方法
$rtn = $u_validate->add('checkname', array($this,'check'),'用户名不唯一');

$rtn = $u_validate->check($data, $rules);
if ($rtn === false) {
echo $u_validate->getError();
}
*
* 示例5:自定义验证方法参数,默认的params 参数失效
* $u_validate = Validate::model();
$data = array("name2"=>"2","name4"=>"ranglen",'tel'=>'13511111111');

$rules = array(
array('name'=>"name2","func"=>array('min',1),"params"=>3),
array('name'=>"name4","func"=>array('ranglen',array(10,20)),"params"=>3),
array('name'=>"tel","func"=>array($this,'check',array(10,20)),"params"=>3),
);

$rtn = $u_validate->check($data, $rules);
if ($rtn === false) {
echo $u_validate->getError();
}
*
*
*
*
* 验证规则参数介绍
* $rules =>array(
* 'name'=>"name2",//验证key 名称,可以理解为数组key
* "func"=>"min",//验证函数 支持!,比如!min
* "params"=>1,//传入的验证参数,比如验证最小值min,传入最小值 7,可以传入任何值
* 'msg'=>'错误消息',//自定义消息,数组,字符串
* "options"=>array(//配置信息其他配置
* 'on'=>false //验证错误后是否继续验证,true 继续 false 终止
* 'op'=>'&&' //操作符 && 与逻辑 或|| 逻辑
* )
* ),

附件 ValidateUtil.class.rar ( 5.18 KB 下载:73 次 )

AD:真正免费,域名+虚机+企业邮箱=0元

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn