限制文本框中的Alpha和特殊字符以及小数精度

时间:2018-02-13 07:46:35

标签: javascript angular typescript

我要求在输入字段中限制alpha和特殊(单点除外)字符。
然后基于过滤后的值,我必须对其他字段进行一些计算

我的Ts文件

@Component({
    selector: 'filter-data',
    template: `<input #input (keydown)="onKeyPress($event)" [(ngModel)]="InputValue" id="Input">`
})

onKeyPress(params: any)
    {       
        if (!this.isKeyPressedNumeric(params)) {            
            return false;
        }

    }
private isKeyPressedNumeric(event: any): boolean {
        debugger
        var inputVal = <HTMLInputElement>document.getElementById("Input");
        var input = inputVal.value;
        input = input + event.key;
        if (input.length >= 2) {
            var txtVal = input;
            return !!/^\d*\.?\d{0,18}$/.test(txtVal);
        }

        const charCode = this.getCharCode(event);
        const charStr = event.key ? event.key : String.fromCharCode(charCode);
        return this.isCharNumeric(charStr);
    }

    private getCharCode(event: any): any {
        event = event || window.event;
        return (typeof event.which == "undefined") ? event.keyCode : event.which;
    }

    private isCharNumeric(charStr: any): boolean {
        var validation = false;

        if (charStr == ".") {
            validation = !!/\./.test(charStr);
        }
        else {
            validation = !!/\d/.test(charStr);
        }
        return validation;
    }

单击退格键时,相应的数字不会被删除 然后我需要限制用户在点之前只输入18位,在点之后输入15位数 过滤数字后,我需要得到最新的计算值 提前致谢

1 个答案:

答案 0 :(得分:1)

你需要的只是

if(params.key === 'Backspace') {
    return true;
}

您的onKeyPress功能应如下所示:

onKeyPress(params: any)
{       
    if(params.key === 'Backspace') {
        return true;
    }
    else if (!this.isKeyPressedNumeric(params)) {            
        return false;
    }
}

<强> WORKING DEMO