Reputation: 6759
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?
Upvotes: 14
Views: 38810
Reputation: 2402
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"/>
Upvotes: 0
Reputation: 31
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:
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.
Upvotes: 3
Reputation: 17289
function Main($scope) {
$scope.regex = "/^-?[0-9][^\.]*$/";
}
input.ng-dirty.ng-invalid { color: red }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<div ng-controller="Main">
<form name="form">
<input type="number" ng-model="person.age" ng-pattern="/^-?[0-9][^\.]*$/"/>
<input type="number" ng-model="person.age1" ng-pattern="{{regex}}" />
</form>
</div>
</div>
try this
$scope.regex = "/^-?[0-9][^\.]*$/";
<input type="number" ng-model="person.age" ng-pattern="{{regex}}"/>
Upvotes: 19