简体   繁体   English

粘贴时如何从输入字段中删除特殊字符?

[英]How to remove special characters from input fields while pasting?

I'm trying to implement functionality where if a user pastes text it should remove < , > , $ and !我正在尝试实现功能,如果用户粘贴文本,它应该删除<>$! . .

The following code works on all inputs.以下代码适用于所有输入。 Currently it disables the paste function.目前它禁用粘贴 function。

function specialCharRestriction() {
  setTimeout(function(e) {
    $('input, textarea').bind("cut copy paste", function(e) {
      e.preventDefault();
    });
    
    $('input:not([type=password]), textarea').on('keypress', function(e) {
      var blockSpecialRegex = /[!$(){}[\]:;<+?\\>]/;
      var key = String.fromCharCode(!e.charCode ? e.which : e.charCode);
      
      if (blockSpecialRegex.test(key)) {
        e.preventDefault();
        return false;
      }
    });
  }, 500);
}

Instead, I want something like this:相反,我想要这样的东西:

$('input').val().replace(regex, '');

This way it can be applied on all inputs and I don't have to select all the inputs one by one.这样它就可以应用于所有输入,我不必 select 一个一个地输入所有输入。 There are more than 100 fields declared in my project so please help with some generic code which can be applied on all input fields.我的项目中声明了 100 多个字段,因此请帮助提供一些可应用于所有输入字段的通用代码。

Edit: I want that whenever someone pastes <Naruto> then only Naruto should be pasted and <> should be omitted.编辑:我希望每当有人粘贴<Naruto>时,应该只粘贴Naruto而 <> 应该被省略。 following code only works once, and then special characters are being pasted.以下代码只工作一次,然后粘贴特殊字符。

 $('input, textarea').bind("input", function(e) { var blockSpecialRegex = /[:$(){}[\];?<+;\\>]/g. let txtOrig = $(this);val(). let txtFinal = txtOrig,replace(blockSpecialRegex; ''): if (txtOrig.== txtFinal) { // Some blocked special chars was found and removed // Warning; this will move the cursor to the end! $(this).val(txtFinal); } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> input1:<input id="txt1"><br> input2:<input id="txt2"><br> input3:<input id="txt3"><br> textarea1:<textarea id="txt4"></textarea><br> textarea2:<textarea id="txt5"></textarea><br> textarea3:<textarea id="txt6"></textarea><br>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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