Reputation: 165
I am trying to create a text input that restricts user from entering more than five decimals and allowing to enter only numbers through 0 - 100. For example:
100 - valid
29.39499 - valid
9.999 - valid
0 - valid
12.0828282 - invalid
101 - invalid
0.0123 - valid
.111 - valid
How would I approach this?
'decimalInput': new FormControl({value: ''}, [Validators.required, Validators.pattern(/^\d*\.?\d*$/), Validators.max(100), Validators.min(0)])
setDecimals(event){
/* My attempt to get less than 5 decimals and less than number 100:
let finalValue = event.target.value + event.key;
let countDecimals = function (value) {
if(Math.floor(value) === value) return 0;
return value.toString().split(".")[1].length || 0;
}
if(parseFloat(finalValue) >= 100 || countDecimals(parseFloat(finalValue)) > 5){
return false;
}*/
let charCode = (event.which) ? event.which : event.key;
if (charCode == 46) {
if (event.target.value.indexOf('.') === -1) {
return true;
} else {
return false;
}
} else {
if (charCode > 31 &&
(charCode < 48 || charCode > 57)){
return false;
}
}
return true;
}
<input type="text" pInputText formControlName="decimalInput" maxlength="8 (keypress)="setDecimals($event)">
Upvotes: 0
Views: 147
Reputation: 10765
Here is a regex which will allow for a whole number of 100 with or without trailing decimal and zeros or a number under 100 with up to five decimal places:
/(^100([.]0{1,5})?)$|(^\d{1,2}([.]\d{1,5})?)$/
Upvotes: 2