How should validation errors be returned to the user?

Hi

In the UserValidator class how should validation errors be returned to the user? I’m thinking a Responder is involved somewhere but as this isn’t an Action class I don’t think it should be invoked within this class or the functions below.

 private function createValidator(): Validator

{

    $validator = $this->validationFactory->createValidator();



    return $validator

        ->notEmptyString('username', 'Input required')

        ->notEmptyString('password', 'Input required')

        ->minLength('password', 8, 'Too short')

        ->maxLength('password', 40, 'Too long')

        ->email('email', false, 'Input required')

        ->inList('user_role_id', [UserRoleType::ROLE_USER, UserRoleType::ROLE_ADMIN], 'Invalid')

        ->notEmptyString('locale', 'Input required')

        ->regex('locale', '/^[a-z]{2}\_[A-Z]{2}$/', 'Invalid')

        ->boolean('enabled', 'Invalid');

}

And this method:

	private function validateNewUser(array $data): void { 
	$errors = [];
	// Here you can also use your preferred validation library
	if (empty($data['username'])) { 
		$errors['username'] = 'Username required'; 
	}
	
	if (empty($data['email'])) { 
		$errors['email'] = 'Email required'; 
	} elseif (filter_var($data['email'], FILTER_VALIDATE_EMAIL) === false) { 
		$errors['email'] = 'Invalid email address'; 
	}

	if ($errors) { 
		throw new ValidationException('Please check your input ', $errors); 
	}
}

Thank you again.

When the validation fails it should throw an ValidationException. See here.

The ValidationExceptionMiddleware is then able to catch this specific ValidationException and generates a JSON response with all the validation error details, the error message and the HTTP status code 422. See here.

If you have a specific question related to this Slim Skeleton project you may also consider to file an issue directly here.

1 Like

Hi,

That makes perfect sense, I’ll look into it further. I want to get the basics nailed before trying to do something a bit more involved.

I’ll keep that in mind, might be better to raise queries on GH.

Thank you.