Reputation: 37
Greetings developers around of the world,
I am trying to deeply understand how to use the "min" and "max" directives in Angular 6, I am aware of the unsupported functionality changes before the Angular 2 version, but now I am using the version 6, so it is supposed to not cause trouble.
However, I was expecting, with the "max" validator, stopping the user of typing more than 9999, Instead of this behaviour, I am only triggering the Validator but not stoping the user, allowing them to type infinite numbers.
How can I achieve this classical "maxlength" behaviour but with an input of type number?
EDIT
I am using PrimeNG components
<input class="ss" type="text" [formControl]="numPolizaCtrl" [(ngModel)]="conceptoForm.numPoliza" pInputText pKeyFilter="pint" placeholder="Nº póliza">
<label *ngIf="numPolizaCtrl.invalid" [ngClass] = "'error'" > Too much numbers. </label>
numPolizaCtrl = new FormControl("", [Validators.max(9999999999), Validators.min(0)]);
I want to stop the user of typing more than "x" number of characters, the same behaviour as the maxLength directive but using an input of type "number".
Thank you all.
Upvotes: 2
Views: 13600
Reputation: 21
Try using regular expressions:
HTML:
<input class="ss" type="text" [formControl]="numPolizaCtrl" [(ngModel)]="conceptoForm.numPoliza" pInputText pKeyFilter="pint" placeholder="Nº póliza"(keydown)=validateNumber($event)>
End your component:
validateNumber(event: KeyboardEvent) {
let regEx = new RegExp('^[0-9]*$');
if(regEx.test(event.key) || event.key=="Backspace" )
return true;
else
return false;
}
Upvotes: 2
Reputation: 318
you can not use maxlength
in input:number
you use min
and max
or use this solution:
in your HTMLTemplete
<input id="txtNumber" placeholder="4 character only" (keydown)="isNumberKey($event)"
type="text" name="txtNumber" maxlength="4">
and in your component
isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
Upvotes: 5