自动验证是thinkphp模型层提供的一种数据验证方法,可以在使用create创建数据对象的时候自动进行数据验证。分为静态验证和动态验证。本文主要和大家介绍thinkphp框架表单验证操作方法,需要的朋友可以参考下,希望能帮助到大家。
一、静态验证
(1)在Home/Controller/路径下新建Index控制器。IndexController
IndexController.class.php页面
注意:静态定义方式因为必须定义模型类,所以只能用D函数实例化模型
create方法是对表单提交的POST数据进行自动验证
<?php namespace Home\Controller; use Think\Controller; class IndexController extends Controller { public function yanzheng(){ $u= D("users");//造一个子类对象 if(empty($_POST)){ $this->show(); }else{ if($u->create()){//验证 echo"验证通过"; }else{ echo $u->getError();//获取错误信息 } } } }
(2)在view/Index文件夹下做yanzheng.html页面
nbsp;html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <meta><title>无标题文档</title><script></script><h1>验证界面</h1>
效果图:
(3)在Model层写静态验证的验证:(路径如图)
UsersModel.class.php
<?php namespace Home\Model; use Think\Model; class UsersModel extends Model{ //添加验证条件 protected $_validate = array( array("uid","require","用户名不能为空!"), //默认情况下用正则进行验证 array("pwd1","require","密码不能为空!"), array("pwd2","require","密码不能为空!"), array("pwd2","pwd1","两次输入的密码不一致",0,"confirm"), // 验证确认密码是否和密码一致 array("age","18,50","年龄不在范围内",0,"between"), array("Email","email","邮箱格式不正确"), ); }
依次验证效果图:
当全部为空时,点击验证
会跳转
输入用户名,其他不输入时,会跳转
两次密码输入不一致时,会提示;年龄不在范围内会提示;邮箱格式不正确时会提示;
输入正确格式内容后
二、动态验证
(1) IndexController.class.php页面
<?php namespace Home\Controller; use Think\Controller; class IndexController extends Controller { public function yz(){ $u= M("users");//造一个父类对象 if(empty($_POST)){ $this->show(); }else{ $rules = array( array("uid","require","用户名不能为空!"), ); if($u->validate($rules)->create()){//验证 $this->ajaxReturn("ok","eval"); }else{ $this->ajaxReturn("no","eval"); } } } }
(2) yz.html页面:
nbsp;html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <meta><title>无标题文档</title><script></script><h1>验证界面</h1>
看一下效果:
当文本框失去焦点时:
当文本框有内容时,再失去焦点:
相关推荐:
以上就是ThinkPHP框架实现表单验证功能代码的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号