Search code examples
c#jquerymodel-view-controllertextboxcopy-paste

How to prevent textbox from copying letters into that?


I am currently working on a C# MVC project. While entering user details into database I need to customize my MobilePhone field to only accept numbers. After some searching I found the below code :

$(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;
});

This code works for me, It only allows numbers to be entered in the Textbox.

But there is a problem, If a user copy some text and then paste the content in the Textbox nothing happens. Then if I press submitt button it submits and occur error.

So then I found this question :Disable Copy or Paste action for text box?

Answer to the question is :

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

But after I tried this I can not copy even numbers to the textbox. Is there any way I can prevent copying of alphabets and special characters only.


Solution

  • Just add some checks in your binding to prevent cut / copy / paste a non-number : 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()
        }
      })
    })