thinkphp表单验证
thinkphp框架提供了表单验证功能,分为静态验证和动态验证。
一、静态验证:
1、首先我们在Admin的IndexController.class.php下写一个方法yanzheng,然后用create方法对表单提交进行验证:
namespace Admin\Controller; use Home\Controller\BaseController; class IndexController extends BaseController{ Public function yanzheng(){ $u = D("users"); if(empty($_POST)){ $this->show(); } else{ if($u->create()){ echo "验证通过"; } else{ echo $u->getError();//获取失败 } } }
2、在view页面创建一个yanzheng,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>
效果图:


我们输入一个用户名来验证:


密码不一致时:


二、动态验证:
(1) YanzhengController.class.php页面
<?php namespace Ceshi\Controller; use Think\Controller; class YanzhengController extends Controller { 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>


浙公网安备 33010602011771号