Respect Validation - Returning a single error

813 Views Asked by At

I'm using Respect Validation. Is it possible to return a single error instead of a bag of errors?

Current I can get the first error using the following:

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
    ]);
}

To do this every time I need to validate is going to get frustrating.

What I'm hoping is that the validation library has a method for returning a single error. If not I'll probably have to look into extending the class to create a method to do the same thing.

Any ideas?

1

There are 1 best solutions below

1
On

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

We've seen validate() that returns true or false and assert() that throws a complete validation report. There is also a check() method that returns an Exception only with the first error found:

use Respect\Validation\Exceptions\ValidationException;

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