TP6.0中的密码验证逻辑、验证器的使用

1. 场景一:只有一个密码框,并且是可选项,留空不修改密码,不留空则修改密码


编辑用户表单

<form action="" method="post">
	用户名 <input type="text" name="username" value="liang" readonly autocomplete="off"><br>
	手机号 <input type="text" name="mobile" value="10086" autocomplete="off"><br>
	新密码 <input type="password" name="password" placeholder="可选项,留空则不修改密码"><br>
	<button>确认修改</button>
</form>

验证器类

<?php
namespace appvalidate;

use thinkValidate;

class User extends Validate
{
    /**
     * 定义验证规则
     */	
	protected $rule = [
        'username' => 'require|unique:user',
        'password' => 'require|length:4,16|confirm',
        'mobile'   => 'require',
    ];

    /**
     * edit 验证场景 编辑用户信息
     */
    public function sceneEdit()
    {
        return $this
            ->remove('username', 'unique')
            ->remove('password', 'require|confirm');
    }
}

使用验证器验证数据

public function edit()
{
	if ($this->request->isPost()) {
		$data = input('post.');
		try {
			validate('appvalidateUser')
				->scene('edit')
				->batch(true)
				->check($data);
		} catch (	hinkexceptionValidateException $e) {
			halt('验证失败', $e->getError());
		}
		echo '通过验证';
	} else {
		return view();	
	}
}

2. 场景二:两个密码框,修改密码时有新密码、确认密码,新密码框不为空时,确认密码才验证


编辑用户表单

<form action="" method="post">
	用户名 <input type="text" name="username" value="liang" readonly autocomplete="off"><br><br>
	手机号 <input type="text" name="mobile" value="10086" autocomplete="off"><br><br>
	新密码 <input type="password" name="password" placeholder="可选项,留空则不修改密码"><br><br>
	确认密码 <input type="password" name="newpassword" placeholder="必须和新密码文本框保持一致"><br><br>
	<button>确认修改</button>
</form>

验证器类

<?php
namespace appvalidate;

use thinkValidate;

class User extends Validate
{
    /**
     * 定义验证规则
     */	
	protected $rule = [
        'username' => 'require|unique:user',
        'password' => 'require|length:4,16|confirm',
        'mobile'   => 'require',
    ];

    /**
     * 定义错误信息
     */	
    protected $message = [
        'newpassword.requireWith' => '确认密码不能为空',
        'newpassword.confirm'     => '两个新密码不一致',
    ];

    /**
     * edit 验证场景 编辑用户信息
     */
    public function sceneEdit()
    {
        return $this
            ->remove('username', 'unique')
            ->remove('password', 'require|confirm')
            ->append('newpassword', 'requireWith:password|confirm:password');
    }  
}

使用验证器验证数据

public function edit()
{
	if ($this->request->isPost()) {
		$data = input('post.');
		try {
			validate('appvalidateUser')
				->scene('edit')
				->batch(true)
				->check($data);
		} catch (	hinkexceptionValidateException $e) {
			halt('验证失败', $e->getError());
		}
		echo '通过验证';
	} else {
		return view();	
	}
}
原文地址:https://www.cnblogs.com/cfmy/p/13394545.html