11

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?

2 Answers 2

21

You can try Angular Reactive form pattern validator

this.savingData = this.formBuilder.group({
  amount: ['', [Validators.required, Validators.pattern("^[0-9]*$")]], // only numbers
});
Sign up to request clarification or add additional context in comments.

4 Comments

@mafortis add regex inside quotes updated answer checkout now
ok works this way amount: ['', [Validators.required, Validators.pattern("^[0-9]*$")]], thanks a lot
@mafortis It will accept other chars as well but the form would be invalid though.
If you are OK with negative numbers too: Validators.pattern('^-?[0-9]*$')
2

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

2 Comments

You mean I replace Validators.required with Validators.pattern()?
You can do this, or save required and use \d*

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.