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.
Use the following fix:
Validators.pattern(/^\+?(?:[1-9]\d*(?:\.\d{1,2})?|0\.(?:[1-9]\d?|\d[1-9]))$/)
The regex demo is here.
Make sure:
/.../
should not be wrapped with any quotes^
and $
at both ends as they will be added automatically.The code above is equal to
Validators.pattern("\\+?(?:[1-9]\\d*(?:\\.\\d{1,2})?|0\\.(?:[1-9]\\d?|\\d[1-9]))")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With