我正在使用尊重验证。是否可以返回单个错误而不是一袋错误?
当前我可以使用以下方法得到第一个错误:
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
]);
}
每次我需要验证时都这样做会令人沮丧。
我希望验证库有一个返回单个错误的方法。如果不是,我可能不得不考虑扩展类以创建一个方法来做同样的事情。
有任何想法吗?