Angular Validator.pattern复杂正则格式验证技术咨询
Angular Validator.pattern for Your Custom String Format
Got it, let's work through this validation requirement step by step. First, let's recap the exact rules we need to enforce based on your example and description:
- The entire string is split into multiple "objects" separated by commas
- Each object has 3 parts separated by semicolons:
- A positive integer (no leading zeros, at least 1 digit)
- Exactly the character
AorD(uppercase; we can adjust for lowercase if needed) - Multiple groups separated by pipes (
|), where each group followsstartTime|endTime|percentage%startTime/endTime: HH:mm format where hours can be 1 or 2 digits (0-23), minutes are 2 digits (00-59) (e.g.,00:00,8:59)percentage: A value between 0-100 followed by%(e.g.,5%,100%)
Step 1: Build the Regex Components
Let's break down each part of the regex to make it easier to understand:
- Positive Integer:
[1-9]\d*→ Ensures no leading zeros and matches any positive whole number (1, 12, 999, etc.) - A/D Character:
[AD]→ Matches exactly uppercaseAorD. If you need case-insensitive matching, use[ADad]or add theiflag to the regex. - Time Format:
(?:[01]?\d|2[0-3]):[0-5]\d→ Validates HH:mm where hours can be 1 or 2 digits (0-23) and minutes are 2 digits (00-59). The(?:...)is a non-capturing group to group the hour logic without creating an unnecessary capture. - Percentage Format:
(?:100|[1-9]?\d)%→ Matches 0-100 followed by%:100handles the exact 100% case[1-9]?\dmatches 0-99 (single digits like5, two digits like35, and even0for 0%)
- Single Time-Percentage Group:
${timeFormat}\\|${timeFormat}\\|${percentageFormat}→ Combines the time and percentage rules into one group (e.g.,00:00|04:59|5%) - Full Object:
${positiveInt};${adChar};(?:${timePercentGroup}(?:\\|${timePercentGroup})*)→ Combines all 3 parts of an object, allowing multiple time-percentage groups separated by pipes. - Full String:
^(?:${singleObject}(?:,${singleObject})*)$→ Ensures the entire string is one or more objects separated by commas, with no extra characters before/after.
Step 2: Implement in Angular
Here's how to use this regex with Angular's Validator.pattern. We'll split the regex into components for readability:
import { Validators, FormControl } from '@angular/forms'; // Define regex components for clarity const positiveInt = '[1-9]\\d*'; const adChar = '[AD]'; const timeFormat = '(?:[01]?\\d|2[0-3]):[0-5]\\d'; const percentFormat = '(?:100|[1-9]?\\d)%'; const timePercentGroup = `${timeFormat}\\|${timeFormat}\\|${percentFormat}`; const singleObject = `${positiveInt};${adChar};(?:${timePercentGroup}(?:\\|${timePercentGroup})*)`; // Build the full regex (use 'i' flag inside RegExp if you need case-insensitive A/D matching) const fullValidationPattern = new RegExp(`^(?:${singleObject}(?:,${singleObject})*)$`); // Use in a FormControl const myInputControl = new FormControl('', [ Validators.required, // Optional, add if the field is mandatory Validators.pattern(fullValidationPattern) ]);
Step 3: Test Edge Cases
Make sure to validate these scenarios to ensure the regex works as expected:
- ✅ Valid example from your question:
1;D;00:00|04:59|5%;05:00|8:59|35%;09:00|14:59|35%;15:00|23:59|25%,2;D;00:00|04:59|5%;05:00|14:59|30%;15:00|23:59|65% - ✅ Single object:
3;A;08:00|17:00|100% - ❌ Invalid integer:
0;D;...(0 is not positive) - ❌ Invalid character:
1;X;...(X is not A/D) - ❌ Invalid time:
1;D;25:00|04:59|5%(hour 25 is invalid) - ❌ Invalid percentage:
1;D;00:00|04:59|101%(101% exceeds 100)
Adjustments if Needed
- If you want to allow lowercase
a/d, modify theadCharto[ADad]or add theiflag when creating the RegExp:new RegExp(..., 'i') - If you need to allow leading zeros in the integer (e.g.,
001), changepositiveIntto\\d+ - If minutes can be 1 digit (e.g.,
8:5), adjust the time format to(?:[01]?\\d|2[0-3]):[0-5]?\\d(though your example uses 2-digit minutes, so this is probably unnecessary)
内容的提问来源于stack exchange,提问作者Jack N
相关产品推荐
相关产品推荐

