angular/forms integer validator
Asked Answered
A

2

10

How can I validate my numeric input field to only accept integer and not any kind of decimal numbers (comma / dot)?

Code

Component

import { FormGroup, FormBuilder, Validators } from '@angular/forms';

this.savingData = this.formBuilder.group({
  amount: ['', Validators.required], // only accept integer 123000
});

HTML

one

<ion-input type="number" min="1" inputmode="numeric" formControlName="amount" placeholder="{{ 'SAVINGS.amount' | translate }}" ></ion-input>

Any idea?

Alyworth answered 18/9, 2020 at 9:46 Comment(0)
A
20

You can try Angular Reactive form pattern validator

this.savingData = this.formBuilder.group({
  amount: ['', [Validators.required, Validators.pattern("^[0-9]*$")]], // only numbers
});
Approval answered 18/9, 2020 at 9:51 Comment(4)
@Alyworth add regex inside quotes updated answer checkout nowApproval
ok works this way amount: ['', [Validators.required, Validators.pattern("^[0-9]*$")]], thanks a lotAlyworth
@Alyworth It will accept other chars as well but the form would be invalid though.Approval
If you are OK with negative numbers too: Validators.pattern('^-?[0-9]*$')Flack
J
2

Try to use pattern like \d+. It is in Validators.pattern()

Jennings answered 18/9, 2020 at 9:49 Comment(2)
You mean I replace Validators.required with Validators.pattern()?Alyworth
You can do this, or save required and use \d*Jennings

© 2022 - 2024 — McMap. All rights reserved.