Angular 5 Validators.pattern regex for only numbers
After trying so many regex expressions, none was working in Safari. So here's what I did...
First, I used the regex when creating the form control:
new FormControl({value: field.value}, [Validators.required, Validators.pattern(/^-?(0|[1-9]\d*)?$/)])
Then, in the input itself I added an (input) event:
<input matInput (input)="validateInput(field)" [placeholder]="field.label" type="number" [formControlName]="field.id" [id]="field.id">
And that function looks like this:
validateInput(field) {
this.detailForm.patchValue({ [field.id]: this.detailForm.controls[field.id].value }); }
}
If you enter an invalid character (e.g. a-z) in Safari, it doesn't store it in the field control's value. It only stores valid values (numbers) there. So I'm just patching the value with the stored value -- if it's valid, with numbers, it's fine; if it's invalid, with other characters, then it will replace the input with an empty string.
Works perfectly on all browsers. Hope this helps someone :)
Allow only integer numbers without symbols.
Validators.pattern(/^[0-9]\d*$/)
Numbers start from one
Validators.min(1)