如果自定义一个 Captcha 验证规则放到 FormRequest 中,就可以把控制器里的验证过程去掉了
我是这么实现的,欢迎指正
(我用的是邮箱验证,在请求验证码的时候就验证邮箱是不是存在)
新建一个验证规则Captcha
app/Rules/Captcha.php
<?php
namespace App\Rules;
use Dingo\Api\Http\FormRequest;
use Illuminate\Contracts\Validation\Rule;
class Captcha implements Rule
{
protected $request = null;
/**
* @var int $inValidFlag
*
* 1 => 超时
* 2 => 验证码不正确
* 3 => 邮箱不正确
*/
protected $inValidFlag = 0;
public function __construct(FormRequest $request)
{
$this->request = $request;
}
public function passes($attribute, $captcha)
{
$result = true;
$cache = \Cache::get($captcha['key']);
\Cache::forget($captcha['key']);
if (empty($cache)) {
$result = false;
$this->inValidFlag = 1;
} elseif (!hash_equals($cache['code'], $captcha['code'])) {
$result = false;
$this->inValidFlag = 2;
} elseif (!hash_equals($cache['email'], $this->request->input('email'))) {
$result = false;
$this->inValidFlag = 3;
}
return $result;
// return empty($cache) ? false :
// hash_equals($cache['code'], $captcha['code']) && hash_equals($cache['email'], $this->request->only('email'));
}
public function message()
{
switch ($this->inValidFlag) {
case 1:
return "验证超时";
case 2:
return "验证码不正确";
case 3:
return "验证邮箱不正确";
}
}
}
在 Request 中调用
public function rules()
{
return [
.
.
.
'captcha' => ['required', 'some other rule', new Captcha($this)],
];
}
本质上都是验证码不正确,看你要求,实际上没有必要把错误信息提示的这么细,验证不通过用户自然会去刷新验证码重新填写的。
我也是喜欢折腾的人,后来我把request封装为里面只有一个rules方法了。
这个框架注重的思想就是业务分层,那个验证层面就是字段验证的。你这样容易让别人看代码找不到思路