From 26e692563b9908427bed9e2be5f5e4e4f120299b Mon Sep 17 00:00:00 2001 From: Yuri Kuznetsov Date: Wed, 5 Oct 2022 14:42:54 +0300 Subject: [PATCH] username validator --- .../FieldValidators/User/UserName/Valid.php | 79 +++++++++++++++++++ .../Resources/metadata/entityDefs/User.json | 5 +- 2 files changed, 83 insertions(+), 1 deletion(-) create mode 100644 application/Espo/Classes/FieldValidators/User/UserName/Valid.php diff --git a/application/Espo/Classes/FieldValidators/User/UserName/Valid.php b/application/Espo/Classes/FieldValidators/User/UserName/Valid.php new file mode 100644 index 0000000000..ac036a6ccf --- /dev/null +++ b/application/Espo/Classes/FieldValidators/User/UserName/Valid.php @@ -0,0 +1,79 @@ + + */ +class Valid implements Validator +{ + private Config $config; + + public function __construct(Config $config) { + $this->config = $config; + } + + /** + * @param User $entity + */ + public function validate(Entity $entity, string $field, Data $data): ?Failure + { + $value = $entity->getUserName(); + + if ($value === null) { + return null; + } + + /** @var ?string $regExp */ + $regExp = $this->config->get('userNameRegularExpression'); + + if (!$regExp) { + throw new RuntimeException("No `userNameRegularExpression` in config."); + } + + if (strpos($value, ' ') !== false) { + return Failure::create(); + } + + if (preg_replace("/{$regExp}/", '_', $value) !== $value) { + return Failure::create(); + } + + return null; + } +} diff --git a/application/Espo/Resources/metadata/entityDefs/User.json b/application/Espo/Resources/metadata/entityDefs/User.json index f03cc236bd..f4f147b793 100644 --- a/application/Espo/Resources/metadata/entityDefs/User.json +++ b/application/Espo/Resources/metadata/entityDefs/User.json @@ -11,7 +11,10 @@ "tooltipText", "inlineEditDisabled" ], - "index": true + "index": true, + "validatorClassNameList": [ + "Espo\\Classes\\FieldValidators\\User\\UserName\\Valid" + ] }, "name": { "type": "personName",