Format validationsErrors

by | Dec 5, 2019 | IT Tips, Wordpress | 0 comments

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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

1
2
// 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 *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.