【问题标题】:Respect Validation - Returning a single error尊重验证 - 返回单个错误
【发布时间】:2016-12-29 00:53:59
【问题描述】:

我正在使用Respect Validation。是否可以返回单个错误而不是一组错误?

当前我可以使用以下方法得到第一个错误:

public function checkUsername(Request $request, Response $response, $args = [])
{
    $body = $request->getParsedBody();
    $usernameValidator = v::key('username', v::alnum()->length(3, 10));

    /*
     * Validate the username
     */
    try
    {
        $usernameValidator->assert($_POST);
    }
    catch(NestedValidationException $e)
    {
        $errors = $e->findMessages([
            'alnum' => 'username must contain only letters and digits',
            'length' => 'username must be between 3 and 10 characters',
            'required' => 'A valid username is required'
        ]);

        $errors = array_values(array_filter($errors, function($error) {
            return !empty($error);
        }));

        throw new AppException($errors[0]);
    }

    /*
     * Find user by username. If $user is empty no user exists
     */
    $user = $this->userRepo->findByUsername($body['username']);

    return $response->withJson([
        'success' => true,
        'data' => [
            'username' => $body['username'],
            'available' => empty($user)
        ],
        'message' => null
    ]);
}

每次我需要验证时都这样做会令人沮丧。

我希望验证库有一个返回单个错误的方法。如果不是,我可能不得不考虑扩展类以创建一个方法来做同样的事情。

有什么想法吗?

【问题讨论】:

    标签: php respect-validation


    【解决方案1】:

    http://respect.github.io/Validation/docs/index.html#validation-methods

    我们已经看到了返回 true 或 false 的 validate() 和抛出完整验证报告的 assert()。还有一个 check() 方法只在发现第一个错误时返回一个异常:

    use Respect\Validation\Exceptions\ValidationException;
    
    try {
        $usernameValidator->check('really messed up screen#name');
    } catch(ValidationException $exception) {
        echo $exception->getMainMessage();
    }
    

    【讨论】:

    • 使用check时是否还可以自定义消息?
    猜你喜欢
    • 2013-02-27
    • 1970-01-01
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    • 1970-01-01
    • 2020-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多