I've written and rigorously tested a regex on Regex101.com, but when implemented into my FormControl Validators.pattern method, it's displaying unexpected behaviour.
This is for the Width input for a package to be mailed. Only positive values, with a maximum of 2-decimal places, a minimum value being (0.01), and a maximum being tested later against an API response (irrelevant).
package_validation_messages = {
'maxWidth': [
{type: 'required', message: 'Width is required.'},
{type: 'pattern', message: 'Invalid Width.'}
]
};
this.packageSizeForm = this.formBuilder.group({
maxWidth: new FormControl('', Validators.compose([
Validators.pattern('^([+]?(([1-9]d*(.d{1,2})?)|0.(([1-9]d?)|(d[1-9]))))$'),
Validators.required
]))
});
<div>
<input formControlName='maxWidth' type='text' required />
<span *ngFor="let validation of package_validation_messages.maxWidth">
<span *ngIf="packageSizeForm.get('maxWidth').hasError(validation.type) && (packageSizeForm.get('maxWidth').dirty || packageSizeForm.get('maxWidth').touched)">{{validation.message}}</span>
</span>
</div>
The following screenshot illustrates my tests from Regex101.com; you can see all the scenarios that should PASS and FAIL.
But, as you can see here, any multi-digit value fails the pattern, contrary to the expected behaviour above.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…