科娃子的博客

专注本地网络

使用ajax在服务器验证表单的程序,抛砖引玉

写这个东西可能用了一个月时间,这一个月时间初学php,初学jquery,自己写的一个开发框架也基本成型了(我觉得ZF、Flea之类的框架不太适合我,也当学习PHP,就这么做了),这套验证程序是从里面抽取出来的,工作原理是:
1、使用jquery和jquery.form插件以ajax方式向服务器post
2、服务端判段数据是否合法,若不,则以json字符串的形式给客户端错误信息,客户端处理并显示错误信息,若合法,则写一段任意的字符串(非JSON),客户端再自定义处理。

不知道怎么样能说明的更加清楚,只有让各位看截图
正常的表单
00035.jpg
有错误时:
00036.jpg

00037.jpg
使用了自定义验证:
00038.jpg

php文件:validation.php
  1 <?php
  2 class validation {
  3 
  4     protected $_errmsg = null;
  5     protected $_filed ;
  6     protected $_val ;
  7     protected $errCount = 0 ;
  8     public $msg = array();
  9     //public $data = array();
 10 
 11     function run ($_rules,$_data) {
 12         //当验证规则和验证数据不为数组时,返回验证成功
 13         if (!is_array($_rules|| !is_array($_data)){
 14             return true;
 15         }
 16         
 17         
 18         //循环所有验证域
 19         foreach ($_data as $key=>$val) {
 20             //如果待验证数据没有对应的验证规则 ,则跳出
 21             if (!array_key_exists($key, $_rules)) {
 22                 break ;
 23             }
 24             
 25             $this->_filed = $key ;
 26             $this->_val = $val;
 27             
 28             
 29             //循环单个验证域中的每个验证规则
 30              
 31             foreach ($_rules[$keyas $param) {
 32                 
 33                     if ($param != 'notrim'){
 34                         $_data[$key= trim($_data[$key]);                        
 35                     }
 36                     //禁止 request 的数据
 37                     if ($param == 'private'){
 38                         sys_error('403:1');
 39                     }        
 40                     //拆分各个参数
 41                     $params = explode(',',$param);
 42                     
 43                     //根据参数的个数来调用验证函数(最多两个)                
 44                     switch (count($params)) {
 45                         case 1:                                                                                                        
 46                             if (call_user_func(array($this, $params[0])))
 47                             {break;}else{break 2;}
 48                         case 2:                            
 49                             if (call_user_func(array($this, $params[0]),$params[1]))
 50                             {break;}else{break 2;}
 51                         case 3:
 52                             if (call_user_func(array($this, $params[0]),$params[1],$params[2]))
 53                             {break;}else{break 2;}
 54                         default:
 55                             if (call_user_func(array($this, $params[0])))
 56                             {break;}else{break 2;}
 57                     }
 58             }
 59                 
 60 
 61         }
 62         
 63     }
 64     //是否通过验证
 65     function passed()
 66     {
 67         return  ( $this->errCount > 0 ) ?  FALSE : TRUE ;
 68     }
 69     //自定义验证
 70     function custom($_errmsg,$_filed)
 71     {    
 72         if ($this->passed()){
 73             $this->_filed = $_filed;
 74             $this->_errmsg = $_errmsg;
 75             return $this->jugde();
 76         }        
 77     }
 78     //通过判断是否设置了错误消息来判定是否通过验证
 79     protected function jugde(){
 80         if ($this->_errmsg == null)
 81         {
 82             $this->msg[$this->_filed] = '';
 83             //$this->data[$this->_filed] = $this->_val;
 84             return true;
 85         }else
 86         {
 87             $this->msg[$this->_filed] = $this->_errmsg;
 88             $this->_errmsg = null;
 89             $this->errCount ++;
 90             return false;
 91         }
 92     }
 93     //验证是否为必填
 94     protected function required () {
 95         if (trim($this->_val) == '') {
 96             $this->_errmsg = '本栏为必填项,请填写。';            
 97         }
 98         return $this->jugde();
 99     }
100     //验证是否为数字
101     protected function numeric(){
102 
103         if (!is_numeric($this->_val)){
104             $this->_errmsg = '请输入数字。';            
105         }
106         return $this->jugde();
107     }
108     //验证是否为整数
109     protected function digit(){
110 
111         if (!ctype_digit($this->_val)){
112             $this->_errmsg = '请输入整数。';            
113         }
114         return $this->jugde();
115 
116     }
117     //验证电子邮件
118     protected function email(){
119         if (!preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $this->_val)){
120             $this->_errmsg = '电子邮件格式不正确,请重新输入。';
121         }
122         return $this->jugde();
123     }
124     //验证数字大小
125     protected function limit($mix,$max){
126 
127         if (ctype_digit($this->_val)){
128             if (!($this->_val >= $mix && $this->_val <= $max)){
129                 $this->_errmsg = '请输入大于'.$mix.',小于'.$max.'的数字。';
130             }
131         }else{
132             $this->_errmsg = '请输入整数。';            
133         }
134         return $this->jugde();
135     }
136     //验证字符串长度
137     protected function len($mix,$max)
138     {
139         $len = iconv_strlen($this->_val,'UTF-8');
140         if (!($len >= $mix && $len <= $max)){
141             $this->_errmsg = '请输入 '.$mix.' 至 '.$max.' 个字符。';
142         }
143         return $this->jugde();
144     }
145     //验证首字母必须为字母的字母、数字和下划线的组合字符串
146     protected function al_num(){
147         if (!preg_match("/^([a-zA-Z])([a-zA-Z0-9\_])*$/ix", $this->_val)){
148             $this->_errmsg='请输入由字母开头,字母、阿拉伯数字和下划线组成的字符。';
149         }
150         return $this->jugde();
151     }
152     //验证字母和数字
153     protected function alnum(){
154         if (!ctype_alnum($this->_val)){
155             $this->_errmsg = '请填写由字母和(或)阿拉伯数字组成的字符。';
156         }
157         return $this->jugde();
158     }
159     //比较值
160     protected function matches($val){
161         if ($this->_val != $val){
162             $this->_errmsg = "两次的输入不一致,请再次确认。";
163         }
164         return $this->jugde();
165     }
166     //验证日期
167     protected function dates(){
168         if (!preg_match("/\d{4}\-\d{2}\-\d{2}/", $this->_val)){
169             $this->_errmsg = '请填写形如 <b>'.date("Y-m-d").'</b> 的日期格式。';
170         }
171         return $this->jugde();
172     }
173     
174     
175 
176 }
177 ?>

js文件:form.valid.js

 1 //设置ajaxSubmit参数
 2 var ajaxFormOption = {
 3     success:function(result){    
 4         //如果返回结果不是json字符串    
 5         if (result.indexOf("{")==-1){    
 6             //隐藏表单验证提示框        
 7             var fv_msg = 'div.' + fvInit ;            
 8             $(fv_msg).hide();
 9             fv_msg = 'div.' + fvError ;    
10             $(fv_msg).hide();
11             fv_msg = 'div.' + fvPassed ;
12             $(fv_msg).hide();    
13             
14         }else{
15             //将json字符串转换为json对象
16             result = eval('(' + result + ')');
17             $.each(result,function(i,n){
18                 var fv_msg = '#'+i+'_msg';
19                 if (result[i]==''){
20                     $(fv_msg).show().html('填写正确。').attr('class',fvPassed);
21                 }else{
22                     $(fv_msg).show().html(n).attr('class',fvError);                    
23                 }
24             });            
25         }        
26     }
27 }
28 //ajaxSubmit
29 $(fvName).submit(function(){
30     $(this).ajaxSubmit(ajaxFormOption);
31     return false;
32 });
33 

html文件 add.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>

<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript" src="/js/jquery.form.js"></script>
<link href="/css/main.css" rel="stylesheet" type="text/css" />
<link href="/css/fm.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="fm"  method="post" action="/valid.php">

<table cellpadding="0" cellspacing="0" border="0" class="main_table">
<tr>
    
<td class="left">会员号码:</td>
    
<td width="220"><input type="text" name="number" class="ipt_small"></td>
    
<td><div id="number_msg"  class="fv_init">&nbsp;</div></td>
</tr>
<tr>
    
<td class="left">会员姓名:</td>
    
<td width="220"><input type="text" name="name" class="ipt_small"></td>
    
<td><div id="name_msg"  class="fv_init">&nbsp;</div></td>
</tr>

<tr>
    
<td class="left">会员性别:</td>
    
<td>
    
<select name="sex">
        
<option value="男"></option>
        
<option value="女"></option>
    
</select>    </td>
    
<td><div id="sex_msg" class="fv_init">&nbsp;</div></td>
</tr>
<tr>
    
<td class="left">会员密码:</td>
    
<td><input type="password" name="password" class="ipt_small"></td>
    
<td><div id="password_msg" class="fv_init">&nbsp;</div></td>
</tr>
<tr>
    
<td class="left">确认密码:</td>
    
<td><input type="password" name="password_confirm" class="ipt_small"></td>
    
<td><div id="password_confirm_msg" class="fv_init">&nbsp;</div></td>
</tr>
<tr>
    
<td class="left">出生年月:</td>
    
<td><input type="text" name="birthday" class="ipt_small"></td>
    
<td><div id="birthday_msg" class="fv_init">&nbsp;</div></td>
</tr>
<tr>
    
<td>&nbsp;</td>
    
<td><input id="submit" type="submit" value="提 交" class="btn_standed"></td>
    
<td>&nbsp;</td>
</tr>
</table>

</form>

<script type="text/javascript">
var fvError = 'fv_error';
var fvPassed  = 'fv_passed';
var fvInit = 'fv_init';
var fvName = '#fm';
</script>
<script type="text/javascript" src="/js/form.valid.js"></script>
<div id="ajax_work">正在载入</div>
</body>
</html>

valid.php 接收表单的POST并返回值给当前页面处理:
<?
include_once('validation.php');

$rules = array(
        
'number' => array('required','numeric'),        
        
'name' => array('required'),
        
'password' => array('required','len,6,18'),
        
'sex' => array('required'),
        
'birthday' => array('required','dates'),
        );

$rules['password_confirm'= array('required','matches,'.$_POST['password']);

$valid = new validation();

$valid->run($rules,$_POST);    
//自定义验证
$valid->custom( checkNumber($_POST['number']) , 'number' );



//自定义验证number的函数
function checkNumber($number) {
    
if($number='123') {
        
return '会员号码已经存在,请重新输入。'
    }
    
return null;
}

//返回结果
if (!$valid->passed()){
    
echo   json_encode($this->valid->msg);
}    
else {
    
echo 1;
}    
?>


说明:需要jquery.js和jquery.form.js,由于对javascript和jquery都一知半解,不知道怎么写类,form.valid.js就写的那么草漏。
用的时候首先载入form.valid.js,然后写四个变量
var fvError = 'fv_error';   //验证不正确时的CSS样式
var fvPassed  = 'fv_passed';//验证正确时的CSS样式
var fvInit = 'fv_init';//验证初始时的CSS样式
var fvName = '#fm';//表单ID

posted on 2007-10-08 17:31 科娃子 阅读(1092) 评论(2)  编辑 收藏 引用 网摘

Feedback

# re: 使用ajax在服务器验证表单的程序,抛砖引玉 2007-11-12 11:08 阳光

哥们,有源码不?发给我一份,非常感谢!jxdyzwh@163.com  回复  更多评论   

# re: 使用ajax在服务器验证表单的程序,抛砖引玉 2007-11-12 16:45 <a href=http://minidx.com>minidxer</a>

CSS设置的也不错  回复  更多评论   



只有注册用户登录后才能发表评论。
网站导航: