3

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]

2
  • It's a number input, so using pattern is useless. The input only accepts numbers. And min is not a validation directive. It's only a standard html attribute that the browser uses to prevent you from spinning belos the minimum. Commented Dec 28, 2018 at 9:51
  • not really, because it is possible to enter the letter "e". 1e1 makes sense but you can also enter e.g. "eeee" Commented Dec 28, 2018 at 14:42

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.