如果自定义一个 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)],
        ];
    }
生命不惜,折腾不止
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 3

本质上都是验证码不正确,看你要求,实际上没有必要把错误信息提示的这么细,验证不通过用户自然会去刷新验证码重新填写的。

5年前 评论

我也是喜欢折腾的人,后来我把request封装为里面只有一个rules方法了。

file

file

5年前 评论

这个框架注重的思想就是业务分层,那个验证层面就是字段验证的。你这样容易让别人看代码找不到思路

5年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!