为什么我在自定义验证后无法输入 % 符号

Why am I unable to enter % sign after my custom validation

本文关键字:输入 符号 自定义 验证 为什么      更新时间:2023-09-26

我有一个要求,我可以输入不超过100的数字(允许100)。此外,这些数字可以有 +-开头的符号和结尾的%号。

我想出了以下函数来验证。但是,即使挣扎了很多,我也无法解决为什么我已经输入了 2 位数字时无法输入 % 符号。

例如:键入 10 后,我无法键入 %(Shift + 5)我的职能:

$scope.checkInputValidation = function(event, value) {
    var key = event.keyCode;
    var currentcharacter = String.fromCharCode(key);
    if (key === 91 || key === 187 || key === 189 || (15 < key && key < 19) || (35 <= key && key <= 40)) {
        return;
    }
    if (isNaN(currentcharacter) && ((currentcharacter !== "%") || (currentcharacter !== "+") || (currentcharacter !== "-") || (currentcharacter !== ""))) {
        if ((key !== 46) && (key !== 8)) {
            event.preventDefault();
            return false;
        }
    }
    var formattedValue;
    if (value.indexOf('%') !== -1) {
        formattedValue = value.replace('%', "");
    } else {
        formattedValue = value;
    }
    if (!isNaN(currentcharacter)) {
        if (parseInt(formattedValue + currentcharacter) > 100 || parseInt(formattedValue + currentcharacter) < -100) {
            event.preventDefault();
            return false;
        }
    }
}

想知道原因以及我应该如何进入%

currentcharacter永远不会包含%字符。您必须结合 event.shiftKey 属性检查 5 (53) 的键代码。

if(key === 53 && event.shiftKey) {
    .. % pressed ..
}