Blogger Information
Blog 65
fans 3
comment 4
visits 67612
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
thinkphp5.1之验证器
无耻的鱼
Original
2057 people have browsed it

验证器操作,个人理解

有助于用户提交的数据的二次验证



2.png


Validate实例

<?php
/**
 * 验证
 */
namespace app\index\model;

use think\Validate as Zhang;

class Validate extends Zhang
{
	// 验证规则
	protected $rule =[
		'name' =>'require|length:2,20',
		'sex' =>'in:0,1',
		'age' =>'require|between:18,29',
		'money' =>'require|gt:2500',
	];

	//错误信息
	protected $message =[
		'name.require' =>'员工姓名不能为空',
		'name.leength' =>'姓名长度不够',

		'sex.in' =>'只能输入男或者女',

		'age.require' =>'年龄不能为空',
		'age.leength' =>'注册年龄不满足',

		'name.require' =>'员工姓名不能为空',
		'name.leength' =>'姓名长度不够',

		'money.require' =>'员工工资不能为空',
		'money.gt' =>'工资必须大于2500'];
}

运行实例 »

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

实例

<?php

namespace app\index\controller;
use think\Controller;
//导入验证器类
use app\index\model\Validate as Zhang;

use think\Validate;

class Dome5 extends Controller
{
	//验证器
	function index()
	{
		$data = [
			'name' => '赵小果',
			'sex' => '1',
			'age' =>19,
			'money'=>'2600'
		];

		$validate= new Validate;
		$validate->check($data);
		dump($validate->getError());
	}

	//简化方式  $this->validate()
	function index1()
	{
		$data = [
			'name' => '赵小果',
			'sex' => '7',
			'age' =>11,
			'money'=>'2600'
		];

		$ruls = 'app\index\model\Validate';

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

		if($res !== true){
			return $res;
		}
		return '成功';

	}
	// 独立验证
	function index3()
	{
		// validate::make()创建验证规则
		// validate->check($data)验证


		// 1.创建验证规则
		$rule =['name' =>'require|length:2,20'];

		// 2.创建错误信息
		$mes =[
			'name.require' =>'员工姓名不能为空',
			'name.leength' =>'姓名长度不够'
		];

		// 3.创建数据
		$date = ['name'=>''];

		// 创建验证规则并返回验证对象
		$vali = Validate::make($rule,$mes);
		$res = $vali->check($date);

		if($res !== true){
			return $vali->getError();
		}
		return '成功';
	} 

}

运行实例 »

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


Correction status:qualified

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