如何过滤粘贴在TextArea中的值

How to Filter the value pasted in TextArea

本文关键字:TextArea 何过滤 过滤      更新时间:2023-09-26

如果我们输入分号分隔的值,就有文本区域,能够处理键盘事件并成功验证。如何在复制粘贴时验证相同内容。

$(function () {
    var kpi = document.getElementById('<%=this.d.ClientID%>').value;
    var tb = $('#<%= TextBox.ClientID %>');
    $(tb).keypress(function (e) {
        var regex = new RegExp("[0-9;]+$");
        var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
        if (regex.test(str) && !($(this).val().match(/;{2,}/))) {
            var as = $(this).val().match(/;/ig) || [];
            var len = as.length;
            if (len < kpi) {
                return true;
            }
        }
        e.preventDefault();
        return false;
    });
    $(tb).keyup(function (e) {
        var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
        if (($(this).val().match(/[;]{2,}/g))) {
            var shortenedString = $(this).val().substr(0, ($(this).val().length - 1));
            $(this).val(shortenedString);
            return true;
        }
        e.preventDefault();
        return false;
    });
    $(tb).on('paste input propertychange', function (e) {
        //Validate interger with ; on paste and rest not allowed
    })
});

您可以尝试使用keyup事件来后期验证输入。在此之前,文本区域中粘贴的值不可用,例如在按键时。您可以通过检查来确定它是否为粘贴,例如:

event.ctrlKey

您可以使用keyup事件,实现的替代尝试可以是这样的:

$(tb).live('keyup', function (e) {
     this.value = this.value.replace(/[;]{2,}/g, "");
       }
 });

这将替换粘贴到文本区域时输入值中的分号。