'How to allow only integer numbers in Angular?
I have a number input in my HTML and I want it to be an integer, not a floating point number.
So, if I have this:
<input type="number" ng-model="person.age" />
Angular will consider a value of 18.4 to be valid. How can I fix this?
Solution 1:[1]
You can also use this ng-pattern="/^(0|\-?[1-9][0-9]*)$/".
Solution 2:[2]
I will share part of my code.
In my .ts file I have the following code:
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
...
export class IntegerComponent implements OnInit {
fgInteger: FormGroup;
...
constructor(private formBuilder: FormBuilder) { }
ngOnInit(): void {
this.fgInteger = this.formBuilder.group({
amount: ['', [Validators.required, ..., Validators.pattern('^\\d+$')]]
});
}
}
The pattern into the .ts worked for me:
- '^' This is the start of the pattern.
- '\d' This means that the value is a digit (0-9).
- '+' Means that this pattern should be used more than 1 time.
- '$' This is the end of the pattern.
Also, into my .html file, I have the following code:
<form id="fgInteger" [formGroup]="fgInteger" novalidate #fform="ngForm" (ngSubmit)="onSubmit()">
<mat-form-field appearance="outline">
<mat-label>Amount:</mat-label>
<input name="amount" formControlName="amount" type="number" min="1" step="1" matInput placeholder="Enter the amount.">
</mat-form-field>
</form>
By the way I'm working with Angular Material.
Solution 3:[3]
This worked for me.
<input type="number" step="1" min="0">
Solution 4:[4]
Here is another option that works great for me. It doesn't allow the user to enter non integer values, but intercepts the keyboard entries if invalid and prevents the character from being typed.
<input type="number" min="0" oninput="validity.valid||(value='');" maxlength="3" placeholder="Quantity"/>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mohaimin Moin |
| Solution 2 | |
| Solution 3 | ian korkie |
| Solution 4 | gadildafissh |
