From 4f02754dfce85c5d660bbdea272aa65d365dfd46 Mon Sep 17 00:00:00 2001 From: Stephan de Wit Date: Mon, 13 Feb 2023 17:00:11 +0100 Subject: [PATCH] MVC / CSVListField: add MaskPerItem toggle to allow regex validation per CSV --- .../OPNsense/Base/FieldTypes/CSVListField.php | 39 +++++++++++++++++-- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/src/opnsense/mvc/app/models/OPNsense/Base/FieldTypes/CSVListField.php b/src/opnsense/mvc/app/models/OPNsense/Base/FieldTypes/CSVListField.php index edecea260..18f42e96d 100644 --- a/src/opnsense/mvc/app/models/OPNsense/Base/FieldTypes/CSVListField.php +++ b/src/opnsense/mvc/app/models/OPNsense/Base/FieldTypes/CSVListField.php @@ -28,7 +28,7 @@ namespace OPNsense\Base\FieldTypes; -use OPNsense\Phalcon\Filter\Validation\Validator\Regex; +use OPNsense\Base\Validators\CallbackValidator; /** * Class CSVListField @@ -64,6 +64,11 @@ class CSVListField extends BaseField */ protected $internalMask = null; + /** + * @var bool marks if regex validation should occur on a per-item basis. + */ + protected $internalMaskPerItem = false; + /** * set validation mask * @param string $value regexp validation mask @@ -73,6 +78,15 @@ class CSVListField extends BaseField $this->internalMask = $value; } + /** + * set mask per csv + * @param bool $value + */ + public function setMaskPerItem($value) + { + $this->internalMaskPerItem = $value; + } + /** * retrieve data including selection options (from setSelectOptions) * @return array @@ -133,8 +147,27 @@ class CSVListField extends BaseField { $validators = parent::getValidators(); if ($this->internalValue != null && $this->internalMask != null) { - $validators[] = new Regex(array('message' => $this->internalValidationMessage, - 'pattern' => trim($this->internalMask))); + $validators[] = new CallbackValidator(["callback" => function($data) { + $regex_match = function($value, $pattern) { + $matches = []; + preg_match(trim($pattern), $value, $matches); + return $matches[0] == $value; + }; + + if ($this->internalMaskPerItem) { + $items = explode($this->separatorchar, $this->internalValue); + foreach ($items as $item) { + if (!$regex_match($item, $this->internalMask)) { + return ["\"" . $item . "\" is invalid. " . $this->internalValidationMessage]; + } + } + } else { + if (!$regex_match($this->internalValue, $this->internalMask)) { + return [$this->internalValidationMessage]; + } + } + return []; + }]); } return $validators; }