Trajce12
Trajce12

Reputation: 361

How can i make validation in angular,so the input cane take just numbers in template approach

I have this kind of input. How can i make validation so the user can enter just numbers,if he enters string then i should give him message that it is forbidden

<input class="form-control"
                 id="price"
                 type="number"
                 placeholder="Price (required)"
                 required
                 [(ngModel)]="product.price"
                 name="price"
                 #priceVar="ngModel"
                 [ngClass]="{'is-invalid': (priceVar.touched ||
                                            priceVar.dirty || 
                                            product.id !== 0) &&
                                            !priceVar.valid }" />

Upvotes: 0

Views: 29

Answers (1)

AliF50
AliF50

Reputation: 18889

Try:

<input class="form-control"
                 id="price"
                 type="number"
                 placeholder="Price (required)"
                 required
                 [(ngModel)]="product.price"
                 name="price"
                 #priceVar="ngModel"
                 pattern="^[1-9]+[0-9]*$" 
                 [ngClass]="{'is-invalid': (priceVar.touched ||
                                            priceVar.dirty || 
                                            product.id !== 0) &&
                                            !priceVar.valid }" />
<div *ngIf="priceVar.invalid && (priceVar.dirty || priceVar.touched)">
  <div *ngIf="priceVar.errors?.pattern">
     priceVar has to be a positive number !!
  </div>
</div>

The pattern on the input ensures that it is a positive number. Having type="number" should do it for you (only numbers allowed).

You can also leverage the required attribute.

Good sources for you (https://angular.io/guide/form-validation, https://itnext.io/working-with-angular-2-form-template-driven-approach-58182fc73150).

Upvotes: 1

Related Questions