简体   繁体   中英

Text input - restrict no more than 5 decimals and more than number 100

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)">

这是一个正则表达式,它允许整数 100 带或不带尾随小数和零,或小于 100 的数字最多有五个小数位:

/(^100([.]0{1,5})?)$|(^\d{1,2}([.]\d{1,5})?)$/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM