Blogger Information
Blog 46
fans 3
comment 1
visits 33309
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
5.25 验证器
吃不起土的少年的博客
Original
775 people have browsed it

实例

<?php
namespace app\validate;

use think\validate;

class Staff extends Validate
{

  protected $rule=[
    'name'=>'require|min:5|max:19',
    'sex'=>'in:0,1',
    'age'=>'require|between:18,60',
    'salary'=>'require|gt:2000'
  ];

  protected $message=[
    'name.require'=>'员工姓名不能为空',
    'name.min'=>'员工姓名不得少于5个字符',
    'name.max'=>'员工姓名不得大于19个字符',
    'sex.in'=>'请选择男或者女',
    'age.require'=>'员工年龄不能为空',
    'age.between'=>'员工年龄必须在18-60周岁之间',
    'salary.require'=>'员工工资不能为空',
    'salary.gt'=>'员工工资不得低于2000元'
  ];
}
 ?>

运行实例 »

点击 "运行实例" 按钮查看在线实例

实例

<?php
namespace app\index\controller;

use think\Controller;
use app\validate\Staff;
use think\Validate;

class Verify extends Controller
{
  //实例化验证
  public function example1(){

    $data=[
      'name'=>'杰洛特',
      'sex'=>0,
      'age'=>62,
      'salary'=>16000
    ];

    $validate =new Staff();
    if(!$validate->check($data)){
      dump($validate->getError());
    }else{
      return '验证通过';
    }
  }

  public function example2(){
    //验证器: 使用控制器内容的验证对象来完成验证: $this->validate($data, $rule)

    // $data =[
    //   'name'=>'卡尔',
    //   'sex'=>1,
    //   'age'=>66,
    //   'salary'=>1606060
    // ];

    $rule='app\validate\Staff';
    $rule=[ 'age'=>'between:18,68'];

    $message =['age.between'=>'年龄必须在18~68岁之间'];

    $data=['age'=>66];

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

  }

  //独立验证
  public function example3(){
    //主要是通过Validate::make()和check()进行验证
		//make($rule,$mess):创建验证规则与错误信息
		//check($data)完成数据验证

    $rule =[
      'age' =>'require|between:1,60'
    ];

    $mes =[
      'age.require' => '年龄必须填写',
			'age.between' => '年龄必须在20到60之间'
    ];

    $data =['age'=> 61];

    $validate = Validate::make($rule,$mes);

    $res =$validate->check($data);

    return $res ?'验证通过':$validate->getError();
  }

}
 ?>

运行实例 »

点击 "运行实例" 按钮查看在线实例


Correction status:Uncorrected

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post