Reputation: 1092
I have a strange problem when trying to validate input[type=number]
in Angular 7 and hope that somebody can help.
<input class="form-control" type="number" name="entranceFee" min="0" [(ngModel)]="entranceFee" #entranceFee="ngModel" pattern="\\d+" [ngClass]="{ 'is-invalid': entranceFee.touched && entranceFee.invalid }" >
<div *ngIf="entranceFee.invalid && entranceFee.touched" class="invalid-feedback">
<div *ngIf="entranceFee.errors.pattern">Only numbers are permitted</div>
<div *ngIf="entranceFee.errors.min">Value cannot be smaller than '0'</div>
</div>
The input shall only accept numbers >= 0
. But whenever I enter a number value (0-9) the form becomes invalid. Why? When I output the ngModel in the console in ngAfterViewChecked()
a number value was written to the model. So how can I validate this form? Is there a bug in the validator or in my head?
The same happens when implementing this code with reactive forms and/or with input[type=text]
Upvotes: 3
Views: 7660
Reputation: 39432
Give this a try:
<input
class="form-control"
type="number"
name="entranceFee"
#entranceFee="ngModel"
[(ngModel)]="entranceFee.value"
pattern="^[+]?([0-9]+(?:[\.][0-9]*)?|\.[0-9]+)$"
[ngClass]="{ 'is-invalid': entranceFee.touched && entranceFee.invalid }" >
<div *ngIf="entranceFee.invalid && entranceFee.touched" class="invalid-feedback">
<div *ngIf="entranceFee.errors.pattern">Only numbers are permitted</div>
<div *ngIf="entranceFee.errors.min">Value cannot be smaller than '0'</div>
</div>
Here's a Working Sample StackBlitz for your ref.
RegEx Courtesy - This Answer
Upvotes: 6