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

求助:HTML表单及Laravel服务端正则验证无法满足号码格式要求

Solution for Your Phone Number Validation Regex

Got it, let's fix this regex issue for you! Your current pattern isn't accounting for the two distinct length requirements based on the starting digit, so here's a tailored solution for both frontend HTML form validation and Laravel backend checks.

Step 1: The Correct Regex Pattern

We'll use a branching regex to handle the two valid cases explicitly:

^(0[0-9]{8}|9[0-9]{9})$

Breakdown:

  • ^ : Matches the start of the string (ensures no extra characters before the number)
  • 0[0-9]{8} : Matches numbers starting with 0, followed by exactly 8 more digits (total 9 digits)
  • | : Acts as an OR operator to separate the two valid patterns
  • 9[0-9]{9} : Matches numbers starting with 9, followed by exactly 9 more digits (total 10 digits)
  • $ : Matches the end of the string (ensures no extra characters after the number)

Step 2: HTML Form Validation

Add the pattern attribute to your input field to enforce this rule on the frontend, plus a title to guide users:

<input 
  type="text" 
  name="phone_number" 
  pattern="^(0[0-9]{8}|9[0-9]{9})$" 
  title="Please enter a valid number: either 9 digits starting with 0, or 10 digits starting with 9"
  required
>

This will trigger the browser's built-in validation when the user submits the form.

Step 3: Laravel Backend Validation

Always validate on the backend too (frontend validation can be bypassed). You can add this rule in your controller or form request class:

Option 1: Inline Controller Validation

public function store(Request $request)
{
    $validated = $request->validate([
        'phone_number' => [
            'required',
            'regex:/^(0[0-9]{8}|9[0-9]{9})$/'
        ]
    ]);

    // Process the request...
}

Option 2: Form Request Class

If you're using a dedicated form request (e.g., StorePhoneNumberRequest), define the rule in the rules() method:

public function rules()
{
    return [
        'phone_number' => ['required', 'regex:/^(0[0-9]{8}|9[0-9]{9})$/']
    ];
}

Test Cases

  • Valid numbers: 016563434, 9849384748
  • Invalid numbers: 01234567 (too short for 0-start), 912345678 (too short for 9-start), 123456789 (wrong starting digit), 0123456789 (too long for 0-start)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:38:47