tp框架使用validate验证器

文件目录

index.php

<?php
namespace app\index\controller;
use app\index\validate\User;
use think\Controller;
use think\Request;
class Index extends Controller
{
    public function index()
    {
    	if(request()->isPost())
    	{
    		$data=[
    			'name'=>input('name'),
    			'pwd'=>input('pwd'),
    		];
    		$validate = new User();
            $result = $validate->scene('edit')->check($data);
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            
    	}
    	else
    	{
    		return $this->fetch('index');
    	}
    }
}

user.php

<?php
namespace app\index\validate;
use think\Validate;
class User extends Validate
{
	protected $rule =[
		'name'  => 'require|max:8|require|min:2',

    	'pwd'  => 'require|max:16|require|min:4',
	]; 

	protected $message  =   [

        'name.require' => '用户姓名不能为空',

        'name.max'     => '用户姓名最大长度为8',

		'name.min'     => '用户姓名最小长度为2',

		'pwd.require' => '密码不能为空',

        'pwd.max'     => '密码最长字符为6',

		'pwd.min'     => '密码最短长度为4',

    ];

    protected $scene = [

        'edit'  =>  ['name','pwd'],

    ];
}
?>

index.html

</!DOCTYPE html>
<html>
<head>
	<title></title>
	<meta charset="utf-8">
</head>
<body>
	<form method="post" action="{url:index/index}">
		姓名:<input type="text" name="name"><br/>
		密码:<input type="password" name="pwd"><br/>
		<input type="hidden" name="hid">
		<input type="submit" name="sub" value="提交">
	</form>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_42249896/article/details/83349467
今日推荐