验证器 模型对应验证处理

原创2019-06-08 22:28:45110
摘要:<?phpnamespace app\validate;//验证器use think\Validate;class Staff extends Validate{ protected $rule = [  'name' => 'require|length:4,15',  'sex' =&

<?php
namespace app\validate;
//验证器
use think\Validate;

class Staff extends Validate
{
 protected $rule = [
  'name' => 'require|length:4,15',
  'sex' => 'in:0,1',
  'age' => 'require|between:18,60',
  'salary' => 'require|gt:1500',
 ];

 //错误信息
 protected $message = [
  'name.require' => '员工姓名不能为空',
  'name.length' => '姓名信息必须在4到15个字符之间',
  'sex.in' => '性别必须是男或者女',
  'age.require' => '年龄不能为空',
  'age.between' => '年龄必须在18到60岁之间',
  'salary.require' => '工资不能为空',
  'salary.gt' => '工资必须大于1500'
 ];
}




<?php
namespace app\index\controller;
use think\Controller;
use app\validate\Staff;//导入验证器类
use think\Validate;
class Verify extends Controller
{
 public function demo1()
 {
  $data = [
   'name' => '杨树木哈哈的身份',
   'age' => 26,
   'salary' => 6000
  ];
  $validate = new Staff();
  if(!$validate->check($data)){
   dump($validate->getError());
  }else {
   return '验证通过~~';
  }
 }

 //验证器简化
 public function demo2()
 {
  //准备要验证的数据
  // $data = [
  //  'name' => '杨树木jhsajfh',
  //  'age' => 26,
  //  'salary' => 6000
  //]; 
  //验证方法
  // $rule = 'app\validate\Staff';

  // $res = $this->validate($data,$rule);

  $data = ['age'=>'24'];
  $rule = ['age'=>'between:18,60'];
  $mess = ['age.between'=>'年龄必须在18到60岁之间'];

  $res = $this->validate($data,$rule,$mess);
  if(true !== $res){
   return $res;
  }
  return '验证成功';
 }

 //独立验证
 public function demo3()
 {
  //创建验证规则
  $rule = ['age'=>'require|between:18,60'];
       //创建错误信息
  $mess = [
   'age.between'=>'年龄必须在18到60岁之间',
   'age.require'=>'年龄必须填写'
  ];
  //创建数据
  $data = ['age'=>'24'];
  //validate::make创建验证规则并返回验证对象
  $validate = Validate::make($rule,$mess);
  $res = $validate->check($data);
  return $res?'验证成功':$validate->getError();
 }
}


批改老师:查无此人批改时间:2019-06-10 10:16:55
老师总结:完成的不错。tp5自带了很多验证器,可以多了解下。继续加油。

发布手记

热门词条