如何在正则表达式中设置必填字符?手机号正则验证需求咨询
Fixing Your Phone Number Validation Regex
Hey there! Let's get that phone number validation sorted out for you. Your current regex has two key issues that are keeping it from meeting your requirements:
- It doesn't enforce the leading
+sign as a mandatory character - The trailing
+in your pattern is unnecessary (it’s actually a regex quantifier modifier here, which isn’t what you want)
The Correct Regex
To validate a 13-character phone number that must start with + followed by 12 digits, use this pattern:
/^\+\d{12}$/
Let's break it down clearly:
^: Anchors the match to the start of the string (ensures nothing comes before the+)\+: Matches the literal+sign (we escape it with a backslash because+is a special character in regex)\d{12}: Matches exactly 12 digits (since the+takes up 1 character, this brings the total length to 13)$: Anchors the match to the end of the string (ensures no extra characters are added after the digits)
Updated Validation Function
Here's your revised function using the correct regex:
function validate_mobile($mobile) { return preg_match('/^\+\d{12}$/', $mobile); }
Quick Test Cases
- Valid number:
+123456789001→ returns1(matches successfully) - Invalid number (no leading
+):1234566780111→ returns0(fails) - Invalid number (too short):
+12345678900→ returns0(only 12 total characters)
内容的提问来源于stack exchange,提问作者silent_coder14
相关产品推荐
相关产品推荐

