日期:2014-05-17  浏览次数:20384 次

ThinkPHP学习笔记(十)在Model中完成自动验证前台的表单数据

index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<form action="__URL__/add" method="post">
	<input type="text" name="username"/>
	<input type="text" name="password"/>
	<input type="text" name="repassword"/>
	<input type="submit" value="提交"/>
	<!--{__NOTOKEN__}-->
</form>

</body>
</html>


UserModel.class.php

<?php
	class UserModel extends Model{
		//参数:
		//1.验证字段(表单中的名称或者辅助字段例如验证码)
		//2.验证规则(结合附加规则一起使用)
		//3.错误提醒
		//4.验证条件(0:1:2:)最好是选择手册中的常量来填写
		//5.附加规则;验证方式:regex;function名;callback;confirm(验证两个字段是否相同);equal;in;unique;
//				常用规则:require:必须存在;email邮箱;url;currency货币;number;
		//6.验证时间
//				是指数据库进行数据库操作时的验证时机(增加数据时,编辑时,全部清空下验证)
//				Model::MODEL_INSERT
//				Model::MODEL_UPDATE
//				Model::MODEL_BOTH
		//自动验证开始
		protected $_validate=array(
			array('username','require','用户名必填',0,0,1),
			array('username','checklen','用户名长度不合法',0,'callback',3),
			array('password','require','用户名必填',0,0,1),
			array('repassword','require','用户名必填',0,0,1),
			array('password','repassword','密码不一致',0,'confirm',1),
//			array('createip','email','邮箱格式不对',0,'regex',1),
		);
		public function checklen($data){
			if (strlen($data)>15||strlen($data)<5)
				return FALSE;
			return true;
		}
		function modelTest(){
			echo '测试的跨模型操作,调用模型中的方法';
		}
	}
?>

AutoAction.class.php

<?php
/**
 * ThinkPHP中的
 * 自动验证(Action中create方法时生效)
 * 		主要写在自定义模型中,完成输入信息的时候对表单或者数据库中的字段进行验证
 * 自动完成
 * 		用户输入的字段并不是用户手动填写的
 * 字段映射
 * 		防止用户从前台看到的字段名称而猜出数据库表中的字段名称
 *
 */
class AutoAction extends Action{
	public function index(){
		$this->display();
	}
	function add(){
		//经过自定义模型
		$user=D('user');
		if ($user->create()) {
			if ($user->add()){
				$this->success("注册成功");
			}else{
				$this->error($user->getError());
			}
		}else{
			$this->error($user->getError());
		}
	}
}
?>