TYPO3 Form:如何校验两个邮箱地址的一致性?
自定义TYPO3 Form邮箱一致性校验器实现
当然有很多开发者已经实现过这类需求,下面是一套可直接复用的自定义校验器方案:
1. 创建校验器类
在你的自定义扩展中新建校验器文件 Classes/Validation/Validator/EmailConfirmationValidator.php,代码如下:
<?php declare(strict_types=1); namespace YourVendor\YourExtension\Validation\Validator; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Validation\Validator\AbstractValidator; use TYPO3\CMS\Form\Domain\Runtime\FormRuntime; use TYPO3\CMS\Form\Exception; class EmailConfirmationValidator extends AbstractValidator { /** * 支持的配置选项:指定要对比的字段名 * @var array */ protected $supportedOptions = [ 'fieldName' => [ '', '需要对比的目标字段名称', 'string', true ] ]; /** * 执行校验逻辑 * @param mixed $value 当前字段的值 * @throws Exception */ public function isValid($value) { /** @var FormRuntime $formRuntime */ $formRuntime = $this->getContext(); if (!$formRuntime instanceof FormRuntime) { throw new Exception('该校验器必须在FormRuntime上下文内使用', 1529226413); } // 获取目标字段的输入值 $comparisonValue = $formRuntime->getFormState()->getFormValue($this->options['fieldName']); // 对比两个值是否一致 if ($value !== $comparisonValue) { $this->addError( $this->translateErrorMessage( 'validation.emailConfirmation.notMatching', 'your_extension_key' ), 1529226414 ); } } }
2. 注册校验器
在扩展的 Configuration/Services.yaml 中注册这个自定义校验器:
services: YourVendor\YourExtension\Validation\Validator\EmailConfirmationValidator: tags: - name: form.validator identifier: 'EmailConfirmation'
3. 添加错误提示翻译
在 Resources/Private/Language/locallang.xlf 中添加多语言错误提示:
<?xml version="1.0" encoding="UTF-8"?> <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"> <file source-language="en" datatype="plaintext" original="messages"> <body> <trans-unit id="validation.emailConfirmation.notMatching"> <source>The email confirmation does not match.</source> <target>邮箱确认与输入内容不一致。</target> </trans-unit> </body> </file> </xliff>
4. 在表单配置中使用
在TYPO3 Form的表单配置文件(如 Forms/your-form.yaml)中,给确认邮箱字段绑定这个校验器:
type: Form identifier: your-form label: '用户表单' renderables: - type: Page identifier: page-1 label: '基本信息' renderables: - type: Text identifier: email label: '邮箱地址' validators: - identifier: EmailAddress - type: Text identifier: email_confirmation label: '确认邮箱' validators: - identifier: EmailAddress - identifier: EmailConfirmation options: fieldName: 'email'
配置完成后,当用户输入的两个邮箱内容不一致时,会自动触发错误提示。
内容的提问来源于stack exchange,提问作者Ralf
相关产品推荐
相关产品推荐

