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

如何修改Django模板中Bootstrap表单的电话号码验证正则?

Django模板+Bootstrap表单验证规则修改方案

现有配置概述

  • 原验证正则:^[+-]?\d(?:-?\d)+$
    仅支持横杠分隔的数字序列,示例:12-65-25-75-84、12-255-0214
  • 配套Bootstrap验证JS:
(() => {
    'use strict'    
    const forms = document.querySelectorAll('.needs-validation')
    
    Array.from(forms).forEach(form => {
        form.addEventListener('submit', event => {
            if (!form.checkValidity()) {
                event.preventDefault()
                event.stopPropagation()
            }

            form.classList.add('was-validated')
        }, false)
    })
})()
  • 原HTML输入框:
<input type="text" class="form-control" id="exampleFormControlInput1" name="tel" id="tel" placeholder="Tel" pattern="^[+-]?\d(?:-?\d)+$" required>

修改后实现方案

新正则表达式

满足「允许横杠/空格分隔数字、总数字位数(不含分隔符)≤15」的需求,优化后的正则:

^[+-]?\d(?:[- ]?\d){0,14}$

规则说明:

  • [+-]?:允许开头带可选的正负号
  • \d:确保输入以至少1位数字开头
  • (?:[- ]?\d){0,14}:后续可跟随0-14组「可选分隔符(横杠/空格)+数字」,确保总数字位数在1-15之间
  • 避免出现连续分隔符或以分隔符结尾的无效格式

更新后的HTML输入框

替换pattern属性并修正重复的id问题:

<input type="text" class="form-control" id="tel" name="tel" placeholder="Tel" pattern="^[+-]?\d(?:[- ]?\d){0,14}$" required>

验证JS代码无需调整

原有的Bootstrap表单提交验证逻辑可直接复用,只需更新输入框的pattern规则即可生效。

符合要求的有效输入示例

  • 12 57 125-98-457
  • 12-28-35-74-12
  • 12 28 35 74 12
  • 123-478 25 12 124-15

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 12:10:31