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

JavaScript表单手机号验证正则匹配问题:如何支持数字间空格?

Fixing Phone Number Validation to Allow Spaces Between Digits

No worries at all—let's get this sorted out quickly. The easiest way to handle spaces in phone numbers is to first clean up the input by removing all spaces before running your validation checks. This way, you don't have to rewrite all your existing regex patterns, which saves you from dealing with messy regex modifications.

Here's the updated code:

var number = jQuery('#phone-number').val().replace(/\s/g, ''); // Remove all spaces from input first
if ((number.match(/(\d)\1\1\1\1\1/)) || 
    (number.match(/(\d)(\d)\1\2\1\2\1\2/)) || 
    (number.match(/123456|234567|345678|456789|567890|987654|876543|765432|654321|543210/)) || 
    (!number.match(/^(0\d{8,10})?$/))) { 
    alert("Please supply a valid phone number"); 
    return false; 
}

Why this works:

  • The replace(/\s/g, '') part strips out all spaces (including multiple spaces, tabs, etc.) from the user's input. So whether someone types 0123 456 7890, 01234567890, or even 0 1 2 3 4 5 6 7 8 9 0, it gets converted to a clean string of digits.
  • Your original validation logic then runs on this cleaned string, so all your existing checks (for repeated digits, sequential numbers, and valid length/format) work exactly as before—no need to tweak each regex.

If you really wanted to keep spaces in the input while validating (instead of cleaning them first), you'd have to modify each regex to allow optional spaces between digits. For example, the repeated digits check would become /(\d)(?:\s*)\1(?:\s*)\1(?:\s*)\1(?:\s*)\1(?:\s*)\1/—but this makes your regexes much longer and harder to read. The input cleaning approach is definitely simpler and more maintainable.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:20:39