【问题标题】:Restrict Alpha and special characters in Text Box along with decimal precision限制文本框中的 Alpha 和特殊字符以及小数精度
【发布时间】:2018-02-13 18:41:54
【问题描述】:

我要求在输入字段中限制 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 位数字
过滤数字后,我需要获取最新的计算值
提前致谢

【问题讨论】:

    标签: javascript angular typescript


    【解决方案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

    【讨论】:

    • 并且还限制用户只能输入点前18位和点后15位
    • 正在测试代码,还需要十进制过滤器
    • 让我修改问题
    • 删除后需要根据更新后的值调用另一种计算方法
    • 在原始问题中您可以看到,更新后的值将传递给另一个计算方法。但是通过您的实现可以删除但无法传递参数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    • 2017-02-21
    • 1970-01-01
    相关资源
    最近更新 更多