I have developed a regex pattern on Regex101.com and thoroughly tested it. However, when I applied it to my FormControl Validators.pattern method, it is exhibiting unexpected behavior.
This regex pattern is meant for validating the Width input of a package that will be sent through mail. It should only accept positive values with up to 2 decimal places, a minimum value of 0.01, and the maximum value will be validated later against an API response (not relevant at the moment).
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 screenshot below showcases the results of my tests conducted on Regex101.com, demonstrating both passing and failing scenarios according to expectations.
However, upon implementation, it appears that the pattern fails to validate multi-digit values, which is contrary to the expected outcome described earlier.