PHP后台验证类(原创)
主要实现的是用户输入内容进行验证,本文是继 ajax提交form,同时提供form表单验证,直接贴上代码<?php
/**
* Form check class
* 格式: uname = array('require'=>'true','max'=>3,'min'=>'1','theme'=> '用户名',reg="tel/qq/num/cn/en/reg")
* @author Administrator
*
*/
class Form{
private $_form_data = array();
private$_error_msg = '';
private $_default_regs = array('num'=>'/^*$/',
'tel'=>'/^((\(\d{2,3}\))|(\d{3}\-))?13\d{9}$/',
'qq'=>'/^\d{5,10}$/',
'cn'=>'',
'en'=>'',
'email'=>'/^+@((+)[.])+{2,4}$/i');
public functionForm($form_data = ''){
$this->_form_data = $form_data;
}
public function check(){
$is_check = true;
foreach ($this->_form_data as $key=>$item){
$is_check = $this->check_item($item);
if(!$is_check){
break;
}
}
return $is_check;
}
public functioninit_form($form_data){
$this->_form_data = $form_data;
}
public function check_item($item){
$is_check = true;
foreach ($item as $key=>$obj){
$check_func = 'check_'.$key;
if(method_exists($this, $check_func)){
$is_check = $this->$check_func($item);
}
if(!$is_check){
break;
}
}
return $is_check;
}
public function error_msg(){
return $this->_error_msg;
}
private function check_require($item){
$require_exp_true = $item['require'] == true && !empty($item['value']);
if($require_exp_true || $item['require']==false){
return true;
}
return $this->init_error($item['theme'].'不能为空!');
}
private function check_max($item){
$str_length = strlen($item['value']);
if($str_length <= $item['max']){
return true;
}
return $this->init_error($item['theme'].'最多'.$item['max'].'个字符');
}
private function check_min($item){
$str_length = strlen($item['value']);
if($str_length >= $item['min']){
return true;
}
return $this->init_error($item['theme'].'最少'.$item['min'].'个字符');
}
private function check_reg($item){
if(array_key_exists($item['reg'], $this->_default_regs)){
return $this->reg_defaults($item);
}
return $this->reg_express($item);
}
private function reg_defaults($item){
$reg = $this->_default_regs[$item['reg']];
if(preg_match($reg,$item['value'])){
return true;
}
return $this->init_error($item['theme'].'格式不对');
}
private function reg_express($item){
}
private function init_error($msg){
$this->_error_msg = $msg;
return false;
}
}
使用方法
1、init_form()初始化数据
数据格式
$form_data = array('username'=> array('require'=>true, 'theme'=> '用户名', 'value'=> $data['username']),
'passwd'=> array('require'=>true, 'theme'=> '密码', 'value'=> $data['passwd']),
'code'=> array('require'=>true, 'theme'=> '验证码', 'value'=> $data['code'], 'max'=> 4 , 'min'=>4, 'reg'=>'num'));
2、check()方法验证,返回true/false
3、error_msg(),返回验证失败信息
页:
[1]