You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OpenCart3中使用PHP校验自定义another_telephone电话号码字段

Opencart 3 自定义电话号码字段PHP校验方案

现有字段情况

你已在供应商店铺表单中新增自定义字段another_telephone(备用电话号码),当前字段表单渲染代码如下:

<div class="form-group ">
   <label class="col-sm-2 control-label" for="input-name"> another telephone</label>
   <div class="col-sm-10">
      <input type="text" name="another_telephone" value="{{another_telephone}}" class="form-control" placeholder="another telephone">
   </div>
</div>

目前该字段默认无输入格式限制,支持输入字母、数字及各类符号,需要通过PHP增加电话号码格式校验,拦截不符合规则的输入内容。

具体实现方法

Opencart 3的表单校验逻辑统一写在对应业务控制器的validateForm方法中,按以下步骤修改即可生效:

  • 第一步:找到供应商店铺对应的控制器文件,在validateForm方法的现有校验规则区块中,加入以下电话号码校验代码:
// 备用电话号码格式校验
if (isset($this->request->post['another_telephone']) && trim($this->request->post['another_telephone']) !== '') {
    // 先过滤号码中常见的分隔符:空格、横杠、括号、加号
    $filtered_phone = preg_replace('/[\s\-()\+]/', '', $this->request->post['another_telephone']);
    // 通用校验规则:纯数字、长度7-15位(覆盖全球固定电话、手机号的标准长度范围)
    if (!preg_match('/^[0-9]{7,15}$/', $filtered_phone)) {
        $this->error['another_telephone'] = '请输入有效的电话号码';
    }
}
// 如果该字段设为必填,保留以下代码;非必填可直接删除
else {
    $this->error['another_telephone'] = '请输入备用电话号码';
}

规则适配提示:如果需要指定特定地区的号码规则,比如仅允许中国大陆11位手机号,可将上述正则替换为/^1[3-9]\d{9}$/,错误提示文本可根据站点实际需求自行修改。

  • 第二步:在控制器渲染模板的代码段中,把校验错误变量传递到模板层,在$data数组中加入以下代码:
$data['error_another_telephone'] = isset($this->error['another_telephone']) ? $this->error['another_telephone'] : '';
  • 第三步:在原有表单字段的模板代码中,输入框下方加入错误提示渲染代码,用户输入不合规时可直接看到提示:
{% if error_another_telephone %}
<div class="text-danger mt-1">{{ error_another_telephone }}</div>
{% endif %}

修改完成后清空Opencart缓存,校验规则即可生效。


内容的提问来源于stack exchange,提问作者Rad Stone

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.01 03:16:04