標籤:inpu head conf 手冊 log 效果 方法 mit span
自動驗證是ThinkPHP模型層提供的一種資料驗證方法,可以在使用create建立資料對象的時候自動進行資料驗證。分為靜態驗證和動態驗證。
關於基礎知識,請查看手冊“自動驗證”一章。
一、靜態驗證
(1)在Ceshi/Controller/路徑下建立Yanzheng控制器。
YanzhengController.class.php頁面
注意:靜態定義方式因為必須定義模型類,所以只能用D函數執行個體化模型
create方法是對錶單提交的POST資料進行自動驗證
<?phpnamespace Ceshi\Controller;use Think\Controller;class YanzhengController extends Controller{ public function jtyz(){ $n= D("users"); if(empty($_POST)){ $this->show(); }else{ //驗證要在model層寫 if($n->create()){ echo "驗證通過!"; }else{ echo $n->getError(); //擷取錯誤資訊 } }} public function _empty(){ echo "您訪問的操作方法不存在!"; } }
(2)在view層做jtyz.html頁面
<!DOCTYPE html><html><head><meta charset="UTF-8"><title></title></head><body><form action="__ACTION__" method="post"><div> 使用者名稱:<input type="text" name="uid"></div><div> 請輸入密碼:<input type="text" name="pwd1"></div><div> 請再次輸入密碼:<input type="text" name="pwd2"></div><div> 年齡:<input type="text" name="age"></div><div> 郵箱:<input type="text" name="email"></div><input type="submit" value="驗證" /></form></body></html>
:
(3)在model層寫靜態驗證的驗證:(路徑)
UsersModel.class.php
<?phpnamespace Ceshi\Model;use Think\Model;class UsersModel extends Model{ protected $_validate = array( //非空驗證 array("uid","require","使用者名稱不可為空"), //相等驗證 array("pwd1","require","密碼不可為空"), array("pwd2","pwd1","兩次密碼輸入不一致","0","confirm"), //範圍驗證 array("age","18,30","年齡不在範圍內","0","between"), //正則驗證 array("email","email","郵箱格式不正確"), );}
依次驗證:
當全部為空白時,點擊驗證
提示:
當輸入使用者名稱後,點擊驗證:
顯示:
兩次密碼輸入不一致時,會提示;年齡不在範圍內會提示;郵箱格式不正確時會提示;否則會提示驗證通過。
二、動態驗證
(1) YanzhengController.class.php頁面
<?phpnamespace Ceshi\Controller;use Think\Controller;class YanzhengController extends Controller{ //非空驗證 靜態// public function jtyz(){ // $n= D("users");//// if(empty($_POST)){// // $this->show();// // }else{ // //驗證要在model層寫// if($n->create()){// echo "驗證通過!";// }else{// echo $n->getError(); //擷取錯誤資訊// } // }//}//動態 public function dtyz(){ if(empty($_POST)){ $this->show(); } else { //驗證規則 $rules = array( array(‘uid‘,‘require‘,‘使用者名稱不可為空!‘), ); $u= M("users"); if($u->validate($rules)->create()){ $this->ajaxReturn("OK","eval"); //如果成功 }else{ $this->ajaxReturn($u->getError(),"eval"); //如果不成功 } }} public function _empty(){ echo "您訪問的操作方法不存在!"; } }
(2) dtyz.html頁面:
<!DOCTYPE html><html><head><meta charset="UTF-8"><title></title><!--引入js--><script src="__ROOT__/Public/js/jquery-1.11.2.min.js"></script></head><body><form action="__ACTION__" method="post"><div> 使用者名稱:<input type="text" name="uid" id="uid"><span id="ts"></span></div><input type="submit" value="驗證" /></form></body><script>//文字框失去焦點時,顯示提示資訊$("#uid").blur(function(){var uid = $(this).val();$.ajax({url:"__ACTION__",data:{uid:uid},type:"POST",dataType:"TEXT",success:function(data){alert(data); if(data.trim()=="OK") { $("#ts").html("驗證通過!"); }else{ $("#ts").html("使用者名稱不可為空!"); }}});})</script></html>
看一下效果:
當文字框失去焦點時:
當文字框有內容時,再失去焦點:
php---tp架構---表單驗證