演示为手机号字段添加正则约束的完整插件代码
解读
国内面试常把“字段校验”作为考察 Drupal 8/9/10 插件体系、配置实体、依赖注入、缓存上下文、配置导出、自动化测试等综合能力的切入点。手机号正则只是业务场景,面试官真正想看的是:
- 是否熟悉 Constraint/ConstraintValidator 插件规范;
- 能否把正则做成可配置、可翻译、可复用;
- 是否掌握插件注解、缓存标签、服务定义、配置导出、单元测试等工程化细节;
- 是否具备中国手机号段(165/166/167/191/195/197/199 等新号段)实时更新意识。
知识点
- Plugin API:Constraint = 插件,ConstraintValidator = 服务
- 注解 vs. yaml:插件发现用 @Constraint,服务定义用 module.services.yml
- 依赖注入:Validator 里只使用注入的 service,杜绝 \Drupal::service()
- 配置化:把正则表达式放到配置实体,支持后台即时改号段
- 翻译:t() 与 Potx 抽取,支持多语言政府站
- 缓存:Constraint 插件对象被序列化到 FieldDefinition,改配置需清缓存
- 测试:KernelTestBase 验证字段保存触发校验;FunctionalTest 验证配置表单
- CI:phpunit.xml 里加 module 路径,GitLab-CI 自动跑
答案
以下代码基于 Drupal 10.2,模块名 mobile_regex,目录结构遵循 Drupal 推荐布局,可直接 drush en mobile_regex 启用。
- mobile_regex/mobile_regex.info.yml
name: 'Mobile Regex'
type: module
description: '为手机号字段提供可配置的中国大陆正则校验'
core_version_requirement: ^10 || ^11
package: Field
dependencies:
- drupal:field
- drupal:node
- mobile_regex/config/schema/mobile_regex.schema.yml
mobile_regex.settings:
type: config_object
label: '手机号正则配置'
mapping:
pattern:
type: string
label: '正则表达式'
error_message:
type: string
label: '错误提示'
- mobile_regex/src/Plugin/Validation/Constraint/MobileConstraint.php
<?php
declare(strict_types=1);
namespace Drupal\mobile_regex\Plugin\Validation\Constraint;
use Symfony\Component\Validator\Constraint;
/**
* @Constraint(
* id = "Mobile",
* label = @Translation("中国大陆手机号", context = "Validation"),
* type = "string"
* )
*/
class MobileConstraint extends Constraint {
public string $pattern;
public string $errorMessage;
public function __construct($options = NULL) {
parent::__construct($options);
$config = \Drupal::config('mobile_regex.settings');
$this->pattern = $config->get('pattern') ?: '/^1(?:3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[189])\d{8}$/';
$this->errorMessage = $config->get('error_message') ?: '请输入有效的中国大陆手机号。';
}
public function validatedBy(): string {
return MobileConstraintValidator::class;
}
}
- mobile_regex/src/Plugin/Validation/Constraint/MobileConstraintValidator.php
<?php
declare(strict_types=1);
namespace Drupal\mobile_regex\Plugin\Validation\Constraint;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class MobileConstraintValidator extends ConstraintValidator {
public function validate($value, Constraint $constraint): void {
if ($value === NULL || $value === '') {
return;
}
if (!preg_match($constraint->pattern, $value)) {
$this->context->addViolation($constraint->errorMessage);
}
}
}
- mobile_regex/config/install/mobile_regex.settings.yml
pattern: '/^1(?:3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[189])\d{8}$/'
error_message: '请输入有效的中国大陆手机号。'
- mobile_regex/src/Form/SettingsForm.php
<?php
declare(strict_types=1);
namespace Drupal\mobile_regex\Form;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
class SettingsForm extends ConfigFormBase {
public function getFormId(): string {
return 'mobile_regex_settings';
}
protected function getEditableConfigNames(): array {
return ['mobile_regex.settings'];
}
public function buildForm(array $form, FormStateInterface $form_state): array {
$config = $this->config('mobile_regex.settings');
$form['pattern'] = [
'#type' => 'textfield',
'#title' => $this->t('正则表达式'),
'#default_value' => $config->get('pattern'),
'#required' => TRUE,
'#description' => $this->t('支持新号段,如 195、197、199。'),
];
$form['error_message'] = [
'#type' => 'textfield',
'#title' => $this->t('错误提示'),
'#default_value' => $config->get('error_message'),
'#required' => TRUE,
];
return parent::buildForm($form, $form_state);
}
public function submitForm(array &$form, FormStateInterface $form_state): void {
$this->config('mobile_regex.settings')
->set('pattern', $form_state->getValue('pattern'))
->set('error_message', $form_state->getValue('error_message'))
->save();
parent::submitForm($form, $form_state);
drupal_flush_all_caches(); // 清字段定义缓存
}
}
- mobile_regex/mobile_regex.routing.yml
mobile_regex.settings:
path: '/admin/config/regional/mobile-regex'
defaults:
_form: '\Drupal\mobile_regex\Form\SettingsForm'
_title: '手机号正则'
requirements:
_permission: 'administer site configuration'
- mobile_regex/tests/src/Kernel/MobileConstraintTest.php
<?php
declare(strict_types=1);
namespace Drupal\Tests\mobile_regex\Kernel;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\node\Entity\NodeType;
use Drupal\Tests\field\Kernel\FieldKernelTestBase;
/**
* @group mobile_regex
*/
class MobileConstraintTest extends FieldKernelTestBase {
public static $modules = ['node', 'mobile_regex'];
protected function setUp(): void {
parent::setUp();
NodeType::create(['type' => 'test'])->save();
FieldStorageConfig::create([
'field_name' => 'field_mobile',
'entity_type' => 'node',
'type' => 'string',
])->save();
FieldConfig::create([
'entity_type' => 'node',
'bundle' => 'test',
'field_name' => 'field_mobile',
'label' => '手机号',
'settings' => [],
'third_party_settings' => [
'mobile_regex' => ['mobile' => []],
],
])->save();
}
public function testValidMobile(): void {
$node = $this->createNode([
'type' => 'test',
'title' => 'Test',
'field_mobile' => '19912345678',
]);
$violations = $node->validate();
$this->assertCount(0, $violations);
}
public function testInvalidMobile(): void {
$node = $this->createNode([
'type' => 'test',
'title' => 'Test',
'field_mobile' => '12345678901',
]);
$violations = $node->validate();
$this->assertCount(1, $violations);
$this->assertEquals('请输入有效的中国大陆手机号。', $violations[0]->getMessage());
}
}
启用模块后,在“管理 » 配置 » 区域与语言 » 手机号正则”里可实时改号段;给任意文本字段勾选 “Mobile” 约束即可生效。
拓展思考
- 动态号段:把工信部最新号段做成 REST 接口,计划任务每天拉取并更新配置,正则自动生成。
- 多国家:把约束扩展成 “PhoneCountry”,通过字段映射国家码,动态选择不同正则。
- Headless:在 JSON:API 提交节点时,同样触发约束,无需额外校验。
- 性能:字段大量批量导入时,用 lazy 验证器跳过空值,减少 preg_match 调用。
- 安全:正则使用 \A \z 防止换行注入;配置表单加 CSRF 保护;错误消息不泄露用户原始输入。
- 测试覆盖:除 Kernel 测试外,编写 GitLab CI job,在 PHP 8.2/8.3、Drupal 10/11 矩阵下跑 PHPUnit,确保升级安全。