Blogger Information
Blog 46
fans 3
comment 2
visits 39248
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
ThinkPHP 数据验证器 2018年4月25日
墨雨的博客
Original
792 people have browsed it

为模型Kc创建验证器

在application\index下创建validate目录,并创建一个与kc表同名的类文件: Kc.php

<?php
namespace app\index\validate;
use think\validate;
//验证器
class Kc extends Validate
{
	//创建验证规则
	protected $rule = [
		'mc' => 'require|min:4|max:20',
		'sl' => 'require|between:0,1000',
		'dj' => 'require|gt:0'
	];
	//自定义错误信息
	protected $message = [
		'mc.require' => '品名不能为空!',
		'mc.min' => '品名不能少于4个字符!',
		'mc.max' => '品名不能多于20个字符!',
		'sl.require' => '库存数量必须填写!',
		'sl.between' => '库存数量必须大于零且小于1000!',
		'dj.require' => '单价必须填写!',
		'dj.gt' => '单价必须大于零!'
	];

}

在application\index\controller下创建Verify.php类用于调用验证器

<?php
namespace app\index\controller;

use think\Controller;
use app\index\validate\Kc;

class Verify extends Controller
{
	public function kcverify(){
		//模拟用户输入的数据
		$data = [
			'mc' => 'qwwwx',
			'sl' => 2,
			'dj' => 10,
		];
		//实例化验证器
		$validate = new Kc();
		if (!$validate->check($data)) {
			dump($validate->getError());
		} else {
			return '验证通过';
		}
	}
}




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