如何防止文本框将字母复制到其中?

How to prevent textbox from copying letters into that?

我目前正在处理一个 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();
});

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

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

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

[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 输入,请尝试

输入类型="tel" 注意一些brawser不支持他们的电话我更喜欢数字

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

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;
   }
}

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

希望对您有所帮助!

只需在您的绑定中添加一些检查以防止剪切/复制/粘贴非数字: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()
    }
  })
})