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?
http://respect.github.io/Validation/docs/index.html#validation-methods