#3 - Validating values and arrays with RegEx

Date: 2018-04-07 12:00 - PHP

Two simple functions to validate values and arrays and return a default value if invalid.

<?php
class Utils {
    public static function validate($value, $regex, $default = null) {
        return (preg_match('%^' . $regex . '$%', $value) !== 1) ? $default : $value;
    }

    public static function validateArray($arr, $expected) {
        $out = array();
        foreach ($expected as $key => $options) {
            if (!array_key_exists($key, $arr) || preg_match('%^' . $options[0] . '$%', $arr[$key]) !== 1)
                $out[$key] = $options[1];
            else
                $out[$key] = $arr[$key];
        }
        return $out;
    }
}

Usage:

<?php
$accountValue = 'abc123';
$account = Utils::validate($accountValue, '[a-zA-Z][a-zA-Z0-9]{1,10}', null);

$passwordValue = '123456';
$password = Utils::validate($passwordValue, '.{8,32}', null);

// validates post values
$values = Utils::validateArray($_POST, array(
    'account' => array('[a-zA-Z][a-zA-Z0-9]{1,10}', null),
    'password' => array('.{8,32}', null),
));

Previous snippet | Next snippet