JavaScript表单手机号验证正则匹配问题:如何支持数字间空格?
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 types0123 456 7890,01234567890, or even0 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

