教程:向注册表单上的字段添加验证

您可能需要为某个字段添加额外的验证,以帮助您的开发人员门户用户。 例如,当用户在门户网站上注册帐户时,您可能想要验证部门名称、员工标识或类似数据。

准备工作

要完成本教程,您必须启用开发人员门户,并拥有管理员权限。 您必须已完成有关 向注册表单添加字段的教程,在其中向注册表单添加了 部门代码 字段。

关于本教程

在本教程中,您向注册表单上的部门代码字段添加一些验证。 此字段对于所有门户网站用户都为必填字段,并且是 DEPnnn 格式的字符串,其中,DEP 是字符串前缀,nnn 是三位数字,例如,DEP123。 通过使用 IBM APIC Portal-addons中已提供的定制模块来完成验证。 但是,有关更多信息,请参阅 定制模块开发: 创建模块框架

请查看我们将在此链接 IBM APIC Portal - addons 中使用的文件。

  • user_field_example.info.yml - 这是模块的元数据,用于定义名称和版本等内容,并包含 Drupal 导入和启用模块所需的其他重要信息。
    name: 'IBM APIC Portal - user field example'
    type: module
    description: 'IBM API Connect Developer Portal tutorial - Example of validating a custom user field'
    package: 'Custom'
    core_version_requirement: ^8 || ^9 || ^10
    version: 1.0.0
    project: 'user_field_example'
    dependencies:
      - ibm_apim
      - auth_apic
  • user_field_example.module - 此模块包含验证功能,并通过使用 hook_form_alter 函数将此验证功能添加到注册表单。
    <?php
    use Drupal\Core\Form\FormStateInterface;
    
    /**
     * Implementation of hook_form_alter() to alter the Sign up form
     */
    function user_field_example_form_alter(&$form, FormStateInterface $form_state, $form_id) {
      if ($form_id === 'user_register_form' ) {
          $form['#validate'][] = 'user_field_example_validate_department_code';
      }
    }
    
    /**
     * Validate the Department code field on the Sign up form.
     *
     * Valid entry = DEPnnn
     *   where n = single figure digit.
     */
    function user_field_example_validate_department_code($form, &$form_state) {
      $dept_code = $form_state->getValue('field_department_code')[0]['value'];
      $valid = preg_match('/^DEP\d{3}$/', $dept_code);
      if (!$valid) {
        $form_state->setErrorByName('field_department_code', t('Invalid department code.'));
      }
    }

克隆并打包验证模块

使用定制模块将验证添加到注册表单上的 Department code 字段。

  1. 克隆定制模块。 以下是使用 Mac 和 Linux 时的示例命令:
    git clone https://github.com/ibm-apiconnect/devportal-addons
  2. 打包定制模块。
    cd devportal-addons/apic_v10/modules
    tar -czf user_field_example.tgz user_field_example/

安装并启用定制模块

  1. 以管理员身份登录开发人员门户
  2. 单击扩展 > 扩展
  3. 点击+ 添加新模块
  4. 在 "上传模块或主题存档"部分,单击 "浏览文件"。
  5. 浏览至 user_field_example.tgz(这是先前创建的已打包的定制模块)并将其选中。 单击打开
  6. 请单击继续
  7. 单击启用新添加的模块链接。
  8. 在筛选框中输入 IBM APIC Portal - user field example
  9. 选择 "IBM APIC Portal - user field example复选框。
  10. 单击启用

现在已安装并启用该模块。

在注册表单中测试验证

  1. 注销管理员用户。
  2. 单击创建一个新帐户
  3. 在所有字段中输入必要的详细信息,将 "Department code设置为 "ABC123
  4. 点击注册
  5. Department code 字段上观察故障消息并突出显示。部门代码字段
  6. Department code 字段更改为 DEP245,重新输入密码,然后单击 Sign up 以查看是否接受有效代码。

您在本教程中执行的操作

您向注册表单上的 部门代码 字段添加了一些验证,然后测试了表单以确保 Department code 字段仅接受格式为 DEPnnn的代码。

实际上,您需要以适用于所有站点的方式添加此配置。 要实现此可用性,需要在定制模块中包含此配置。 有关更多信息,请参阅 Drupal 定制模块