Validator implementation in Slim PHP Framework

To handle the request params those coming in REST api, There are multiple ways to cater the problem. But if we have smarter way to resolve it then that will be cake walk.

So, Here i would like to share the information to validate the request param weather it’s coming in POST or GET HTTP method.

Inside SLIM framework, Please follow the below steps:

  1. Install the library “respect/validation” with the help of composer i.e. composer require respect/validation
  2. On step 1, composer will install the all dependent library also.
  3. Now open your Controller file, use the validation class like as “use Respect\Validation\Validator as v;” in top of class.
  4. Now you are ready to use the magic of validator class inside action method.
  5. Small code snippet to use this
protected function action(): Response
    {
        $formData = $this->getFormData();
        $typeFor = '';
        $studentMovement = new StudentMovement();
        $dt = new DateTime();
        $dt->format('Y-m-d H:i:s');

        try {
            $studentIdValidator = v::attribute('student_id', v::allOf(
                v::notEmpty(),
                v::intVal()
            ));
            $studentIdValidator->assert($formData);
            $student = $this->studentRepository->findStudentOfId((int) $formData->student_id);
            $studentMovement->setStudent($student);
        } catch (Exception $e) {
            throw new Exceptions\BadRequestException('The valid student_id is required');
        }

6. Some other sample cases for the validator:

//To check the type and assert it's value
$reasonIdValidator = v::attribute('reason_id', v::allOf(
                v::notEmpty(),
                v::intVal()
            ));
$reasonIdValidator->assert($formData);

//To check the type and value, assign custom message if validation fail 
$timeValidator = v::attribute('time', v::notEmpty())->setTemplate('Provide valid time value');
$timeValidator->assert($formData);

//If any one of validator fail and attribute may be optional
$latechekinType = v::attribute('latecheckin_type', v::oneOf(
                v::stringType(),
                v::nullType()
            ), false)->setTemplate('Valid type should be string type');

For more data type handle please see the complete documentation in detail

  • 23
    Shares