【问题标题】:How to prevent textbox from copying letters into that?如何防止文本框将字母复制到其中?
【发布时间】:2017-10-12 09:52:23
【问题描述】:

我目前正在开发一个 C# MVC 项目。在将用户详细信息输入数据库时​​,我需要自定义我的 MobilePhone 字段以仅接受数字。经过一番搜索,我找到了以下代码:

$(document).on("keypress","#MobilePhone", function (e) {
    var regex = new RegExp("^[0-9]\d*$");
    var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
    if (regex.test(str)) {
        return true;
    }
    e.preventDefault();
    return false;
});

此代码适用于我,它只允许在文本框中输入数字。

但是有一个问题,如果用户复制一些文本,然后将内容粘贴到文本框中,则没有任何反应。然后,如果我按下提交按钮,它就会提交并发生错误。

然后我发现了这个问题:Disable Copy or Paste action for text box?

问题的答案是:

$('#email').bind("cut copy paste",function(e) {
   e.preventDefault();
});

但是在我尝试这个之后,我无法将偶数复制到文本框中。有什么办法可以防止只复制字母和特殊字符。

【问题讨论】:

  • 您需要在第二个bind 方法中添加逻辑来检查/处理正在粘贴的内容。目前e.preventDefault() 只是阻止一切
  • 可以使用内置的<input type="number">,并使用min和max属性来控制最小值和最大值。

标签: c# jquery model-view-controller textbox copy-paste


【解决方案1】:

只需在绑定中添加一些检查,以防止剪切/复制/粘贴非数字:https://jsfiddle.net/hswtutd9/

$(function() {
  $("#email").bind("cut copy paste", function(e) {
    const data = e.originalEvent.clipboardData.getData("Text")

    if(! /\d./.test(data)) {
      e.preventDefault()
    }
  })
})

【讨论】:

    【解决方案2】:

    你为什么使用文本作为输入类型????

    如果您使用强类型视图,即编辑器,则只需使用数据注释

    [DataType(DataType.PhoneNumber)]
    public string PhoneNumber{get;set;}   //i've used string here believing you initially made it as string and hence not effecting the code elsewhere 
    

    如果你使用 html 输入试试

    input type ="tel" 注意一些 brawser 不支持他们的 tel 我更喜欢数字

    【讨论】:

      【解决方案3】:

      您可以将电话号码验证码放在一个函数中,如果两个地方都像这样调用:

      function IsValidPhoneNumber(number) {
        var regex = new RegExp("^[0-9]\d*$");
      
         if (regex.test(number)) {
            return true;
         }
        return false;
      }
      

      现在你可以在两个地方都这样称呼它:

      $(document).on("keypress","#MobilePhone", function (e) {
      
         if(!IsValidPhoneNumber($(this).val())) {
      
            e.preventDefault();
            return false;
         }
      }
      
      $('#MobilePhone').bind("cut copy paste",function(e) {
      
         if(!IsValidPhoneNumber($(this).val())) {
      
            e.preventDefault();
            return false;
         }
      });
      

      或者更好的是在单个事件中:

      $(document).on("cut copy paste keypress","#MobilePhone", function (e) {
      
         if(!IsValidPhoneNumber($(this).val())) {
      
            e.preventDefault();
            return false;
         }
      }
      

      现在如果值满足正则表达式,它将允许复制,您可能需要调整函数以检查整数,但这应该让您知道如何允许复制。

      希望对您有所帮助!

      【讨论】:

        猜你喜欢
        • 2012-03-10
        • 2015-02-14
        • 1970-01-01
        • 1970-01-01
        • 2011-09-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-25
        相关资源
        最近更新 更多