Skip to content

Instantly share code, notes, and snippets.

@mnoskov
Created March 3, 2021 06:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mnoskov/74228bb7a91c17120da666cb4ce9a6e8 to your computer and use it in GitHub Desktop.
Save mnoskov/74228bb7a91c17120da666cb4ce9a6e8 to your computer and use it in GitHub Desktop.
Bitrix phone validator
<?php
class CFormCustomValidatorPhone
{
public function GetDescription()
{
return [
'NAME' => 'custom_phone', // идентификатор
'DESCRIPTION' => 'Телефон', // наименование
'TYPES' => ['text'], // типы полей
'SETTINGS' => ['CFormCustomValidatorPhone', 'GetSettings'],
'CONVERT_TO_DB' => ['CFormCustomValidatorPhone', 'ToDB'],
'CONVERT_FROM_DB' => ['CFormCustomValidatorPhone', 'FromDB'],
'HANDLER' => ['CFormCustomValidatorPhone', 'DoValidate'],
];
}
public function GetSettings()
{
return [
'MASK' => [
'TITLE' => 'Маска для проверки',
'TYPE' => 'TEXT',
'DEFAULT' => '/^(\+7|8) ?[\(]\d{3}[\)] ?\d{3}[- ]\d{2}[- ]\d{2}$/',
],
];
}
public function ToDB($arParams)
{
return serialize($arParams);
}
public function FromDB($strParams)
{
return unserialize($strParams);
}
public function DoValidate($arParams, $arQuestion, $arAnswers, $arValues)
{
global $APPLICATION;
foreach ($arValues as $value) {
if (empty($value)) {
continue;
}
if (!is_scalar($value)) {
return false;
}
try {
if (!@preg_match($arParams['MASK'], $value)) {
throw new Exception('формат телефона неверный');
}
} catch (Exception $e) {
$APPLICATION->ThrowException('#FIELD_NAME#: ' . $e->getMessage());
return false;
}
}
return true;
}
}
AddEventHandler('form', 'onFormValidatorBuildList', [
'CFormCustomValidatorPhone',
'GetDescription'
]);
<?php
include_once __DIR__ . '/CFormCustomValidatorPhone.php';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment