转:http://blog.163.com/zhuxun_why/blog/static/26813905020171861417642/
表单验证真的很简单 相比较yii的表单验证tp做的很人性 也能达到效果
相关规则:
// 验证规则默认提示信息
protected static $typeMsg = [
'require' => ':attribute不能为空',
'number' => ':attribute必须是数字',
'float' => ':attribute必须是浮点数',
'boolean' => ':attribute必须是布尔值',
'email' => ':attribute格式不符',
'array' => ':attribute必须是数组',
'accepted' => ':attribute必须是yes、on或者1',
'date' => ':attribute格式不符合',
'file' => ':attribute不是有效的上传文件',
'image' => ':attribute不是有效的图像文件',
'alpha' => ':attribute只能是字母',
'alphaNum' => ':attribute只能是字母和数字',
'alphaDash' => ':attribute只能是字母、数字和下划线_及破折号-',
'activeUrl' => ':attribute不是有效的域名或者IP',
'chs' => ':attribute只能是汉字',
'chsAlpha' => ':attribute只能是汉字、字母',
'chsAlphaNum' => ':attribute只能是汉字、字母和数字',
'chsDash' => ':attribute只能是汉字、字母、数字和下划线_及破折号-',
'url' => ':attribute不是有效的URL地址',
'ip' => ':attribute不是有效的IP地址',
'dateFormat' => ':attribute必须使用日期格式 :rule',
'in' => ':attribute必须在 :rule 范围内',
'notIn' => ':attribute不能在 :rule 范围内',
'between' => ':attribute只能在 :1 - :2 之间',
'notBetween' => ':attribute不能在 :1 - :2 之间',
'length' => ':attribute长度不符合要求 :rule',
'max' => ':attribute长度不能超过 :rule',
'min' => ':attribute长度不能小于 :rule',
'after' => ':attribute日期不能小于 :rule',
'before' => ':attribute日期不能超过 :rule',
'expire' => '不在有效期内 :rule',
'allowIp' => '不允许的IP访问',
'denyIp' => '禁止的IP访问',
'confirm' => ':attribute和确认字段:2不一致',
'different' => ':attribute和比较字段:2不能相同',
'egt' => ':attribute必须大于等于 :rule',
'gt' => ':attribute必须大于 :rule',
'elt' => ':attribute必须小于等于 :rule',
'lt' => ':attribute必须小于 :rule',
'eq' => ':attribute必须等于 :rule',
'unique' => ':attribute已存在',
'regex' => ':attribute不符合指定规则',
'method' => '无效的请求类型',
'token' => '令牌数据无效',
'fileSize' => '上传文件大小不符',
'fileExt' => '上传文件后缀不符',
'fileMime' => '上传文件类型不符',
];
全在
think\Validate 里面 我直接上代码:
/**
* create by phpstorm
* user zhu_xun
* create_time 2017/2/8
* controller_name Login
* content 登录 找回密码类控制器
* */
namespace app\index\controller;
use think\Validate; //一定要use 这个方法
class Login extends Validate //继承
{
//这里是描述 可不要
protected $scene = [
'edit' => ['user','password'],
];
public function index()
{
if(input('post.')){
$info = input('post.');//接收值
//这是验证规则 中间的 | 隔开多个验证规则
$rule = [
'user' => 'require|token', //我这里的token 是令牌验证
'password' => 'require',
];
//错误信息提示
$msg = [
'user.require' => '登录账号不能为空',
'password.require' => '密码不能为空',
];
// 实例化验证类
$validate = new Validate($rule, $msg);
$result = $validate->check($info);
$error = $validate->getError();//打印错误规则
if(empty($error)){
echo 2;
}else{
echo $error; //错误信息
}
}else{
return view('login',['name'=>'thinkphp']);
}
}
方法有很多 但是我就用的这个 感觉很简单
验证规则支持对表单的令牌验证,首先需要在你的表单里面增加下面隐藏域:
或者
{:token()}
protected $rule = [ 'name' => 'require|max:25|token', 'email' => 'email',
];
简单吧
您有利他之心,乐于分享,
您遇到php问题,百度且问了其他群之后仍没得到解答,
欢迎加入,PHP技术问答群,QQ群:292626152