Home > Mobile >  how to make inputs in angular accept only specific data
how to make inputs in angular accept only specific data

Time:10-02

Im working on an angular project and i want to create an input that only accepts 3 values 0, 0.5, 1 and if the user enters for example 0.4 he will get an error message and tell him to enter only one of the 3 values{ 0 / 0.5 / 1 }.

CodePudding user response:

You can use Angular template-driven form with pattern validator, like below:

app.component.ts

export class AppComponent {
  model: any = {};
}

app.component.html

<input
  type="number"
  name="quantity"
  [(ngModel)]="model.quantity"
  #quantity="ngModel"
  pattern="^(0|0.5|1)$"
  required
/>
<div *ngIf="quantity.invalid && (quantity?.dirty || quantity?.touched)">
  Quantity is invalid! Only allowed values are: 0, 0.5, 1
</div>

A Stackblitz to try on: Link

  • Related