表单验证
静态方式
首先需要建一个相应表的数据模型 如infomodel.class .php 在模型中 建成员变量 再建数组 在数组中添加验证规则 需要通过$_validate属性定义验证规则
格式为 array(
array(验证字段1,验证规则,错误提示,[验证条件,附加规则,验证时间]),
array(验证字段2,验证规则,错误提示,[验证条件,附加规则,验证时间]),
......
);
<?php namespace HomeModel; use ThinkModel; class InfoModel extends Model { protected $_validate=array( //array("Code","require","代号不能为空",0,"regex",3), //array("Name","","姓名不能重复",0,"unique",3), //array("QueRen","Sex","两次输入内容不一致",0,"confirm",3), //array("QueRen","123","输入内容不正确",0,"equal",3), //array("QueRen","18,50","输入年龄要在18-50之间",0,"between",3), //array("QueRen","email","邮箱格式不正确",0,"regex",3), ); }
自动收集表单 if (!$m->create()) { echo $m->getError(); } else { echo "验证通过"; /* $bs = $m->add(); if ($bs) { $this->success("添加成功", "Test"); } else { $this->error("添加失败"); }*/ }
动态方式
使用模型类的validate方法动态创建自动验证规则。
自动在收集表单的时候验证 字符串会被当做0
//动态验证 $rules=array( array("Code","require","代号不能为空",0,"regex",3), ); if (!$m->validate($rules)->create()) { echo $m->getError(); } else { echo "验证通过"; /* $bs = $m->add(); if ($bs) { $this->success("添加成功", "Test"); } else { $this->error("添加失败"); }*/ }
利用ajax实时验证
需注意三点 jQuery引入 URL 返回
1.jQuery引入
<load href="__PUBLIC__/JS/jquery-1.11.2.min.js" /><js href="/Public/Js/Common.js" />
<css href="/Public/Css/common.css" />
__CONTROLLER__/ChuLi 后边为方法名
2.URL书写
3.ajax的返回 $this->ajaxReturn($name,"eval"); 有xml json eval(字符串) 默认为json
ajax根据输入代号查看姓名
<input id="code" type="text" name="code"> <input id="btn" type="button" value="查看姓名"> </body> <script type="text/javascript"> $(document).ready(function (e) { $("#btn").click(function () { var code=$("#code").val(); $.ajax({ url:"__CONTROLLER__/ChuLi", data:{code:code}, type:"POSt", dataType:"TEXT", success:function (data) { alert(data); } }); }) }) </script>
function ChuLi() { $code=$_POST["code"]; $m=D("info"); $attr=$m->find($code); $name=$attr["name"]; $this->ajaxReturn($name,"eval"); }
ajax实现实时判断
<div> 代号:<input id="dh" type="text" name="Code" /> <span id="dhyz"></span> </div> <script type="text/javascript"> $(document).ready(function (e) { $("#dh").blur(function () { var code=$(this).val(); $.ajax({ url:"__CONTROLLER__/YanZheng", data:{Code:code},//注意此时额提交根post提交一样 需注意是否与列名一样 type:"POSt", dataType:"TEXT", success:function (data) { if(data.trim()=="OK") { $("#dhyz").html("验证通过"); $("#dhyz").css("color","green"); } else { $("#dhyz").html(data); $("#dhyz").css("color","red"); } } }); }) }) </script>
function YanZheng() { $m=D("info"); $str=""; $rules=array( array("Code","require","代号不能为空",0,"regex",3), ); if (!$m->validate($rules)->create()) { $str=$m->getError(); } else { $str="OK"; } $this->ajaxReturn($str,"eval"); }