[英]Text input - restrict no more than 5 decimals and more than number 100
我正在嘗試創建一個文本輸入,它限制用戶輸入超過五位小數,並只允許輸入 0 - 100 之間的數字。例如:
100 - valid
29.39499 - valid
9.999 - valid
0 - valid
12.0828282 - invalid
101 - invalid
0.0123 - valid
.111 - valid
我將如何處理這個問題?
'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)">
這是一個正則表達式,它允許整數 100 帶或不帶尾隨小數和零,或小於 100 的數字最多有五個小數位:
/(^100([.]0{1,5})?)$|(^\d{1,2}([.]\d{1,5})?)$/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.