Format validationsErrors

Written by James McDonald

December 5, 2019

A recursive function that takes a validation error array and return a string with all the different errors concatenated into a formatted string

Further to my previous posting

This function will walk the validationErrors array and return the error messages.

function formatValidationErrors($validationErrors = [], $errorMessage = null)
{
    // get Validation errors and append them into a string

    foreach ($validationErrors as $key => $value) {
        if (is_array($value)) {
            $errorMessage = formatValidationErrors($value, $errorMessage);
        } else {
            if ($errorMessage) {
                $errorMessage .= sprintf(". <strong>%s: </strong>", $value);
            } else {
                $errorMessage = sprintf("<strong>%s</strong>", $value);
            }
        }
    }

    return $errorMessage;
}

Calling the code from your controller

// app/Controller/CartonController.php
$errorText = $this->Carton->formatValidationErrors($this->Carton->validationErrors);

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

You May Also Like…

Scam call from “Telstra”

Just had a call from a man with a sub-continental accent from caller ID 0734946596 Told me there was problem with my...

PC Build

I recently built myself a PC using the SilverStone SG13 Case. I am planning to use it as a Hot Spare. So any client...