求助:HTML表单及Laravel服务端正则验证无法满足号码格式要求
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 with0, followed by exactly 8 more digits (total 9 digits)|: Acts as an OR operator to separate the two valid patterns9[0-9]{9}: Matches numbers starting with9, 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

