Search code examples
validationfat-free-frameworkrespect-validation

Respect\Validation\Validator - using an array while catching errors


I am attempting to catch errors utilizing the Respect\Validation\Validator opensource PHP class. I used their example to create an array of checks. Although that seems to work ok, I then attempted to catch any error messages so that I could display it to the user. I saw no method to do so as a full array (check everything, store all messages in an array). So instead, I tried to cycle through using the check method in Validator.

This is inside of a class method, using the F3 (Fat Free) Framework.

I end up with the following error:

Cannot use object of type Respect\Validation\Validator as array

The code is below. What is the proper way to perform this task using arrays here? Thank you for the assistance!

$registerValidator = 
    Respect\Validation\Validator::attribute('email', Respect\Validation\Validator::email()->length(1,null)->notEmpty())
        ->attribute('address', Respect\Validation\Validator::stringType()->length(3,null)->notEmpty())
        ->attribute('city', Respect\Validation\Validator::alpha()->length(2,60)->notEmpty())
        ->attribute('state', Respect\Validation\Validator::alpha()->length(2,2)->notEmpty())
        ->attribute('zip', Respect\Validation\Validator::intType()->length(5,5)->notEmpty());
    
foreach($this->f3->get('POST') as $key => $value){
    try{
        $registerValidator[$key]->check($value);
    } catch (\InvalidArgumentException $e) {
        $errors = $e->getMainMessage();
        $this->userMessage($errors, 'warning');
        $this->f3->reroute('/register');
    }
}

I have also tried to use the assert method as found in their docs, but utilizing the below change, I get a different error at a 500 Server Internal Error, instead of seeing my echo:

try{
    $registerValidator->assert($this->f3->get('POST'));
} catch (Respect\Validation\Validator\NestedValidationException $e) {
    $errors = $e->getMessages();
    echo($errors); // I can't even get here.
    foreach($errors as $error){
        $this->userMessage($error, 'warning');
    }
    $this->f3->reroute('/register');
}

With this 500 Error, rather than seeing my Echo, so the page stops loading entirely.

All of the required rules must pass for ...


Solution

  • You cannot really use the Validator class as an array like you're doing on $registerValidator[$key]->check($value). The object in $registerValidator variable contain the chain of rules to validate an input.

    In your case I believe the input is the array coming from the POST, so first of all you should use the Key validator instead of Attribute.

    However the real reason why you cannot catch the errors is because you have a typo on your catch statement, the class name should be Respect\Validation\Exceptions\NestedValidationException like it's stated in the documentation, not Respect\Validation\Validator\NestedValidationException.