Curious Developer
Curious Developer

Reputation: 725

Parse the content we get from copy and paste using jquery

I am working on a project and I am stuck on a very weird issue. I have to restrict what content we receive from copy and paste on an input box. For instance, if only numbers are allowed in the input boxes. I would like user to not be able to paste anything other than numbers. Or if they paste anything and leave the input box then remove anything that is not a number. Is it possible using jquery?

<input onKeyPress="return filterNumber(event)" type="text" id="phone">

function filterNumber(evt){
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}

The above function 'filterNumber' won't allow user to enter anything other than number while they type. But it won't prevent them from pasting anything like alphabets, symbols and numbers.

I tried google but I didn't find any solution for this.

Can anyone help?

Upvotes: 0

Views: 316

Answers (2)

Mitya
Mitya

Reputation: 34576

First of all, don't listen for key events for pasting. What if I paste with the mouse? There's a dedicated paste event.

The second advantage of this approach is that the event data contains clipboard data, which you can retrieve and interrogate before you even allow it into your text field.

let ta = document.querySelector('textarea');
ta.addEventListener('paste', evt => {
    let pasted = evt.clipboardData.getData('text/plain');
    if (/\D/.test(pasted)) { //<-- contains any non-numeric chars?
        evt.preventDefault();
        alert('Only numbers allowed, matey!');
    }
});

If the pasted input contains non-numeric characters, we cancel the operation by suppressing the event's default action (which is, of course, to paste the text.)

Fiddle

Upvotes: 2

T&#226;n
T&#226;n

Reputation: 1

You can use regex to do that.

Or if they paste anything and leave the input box then remove anything that is not a number

In this example, when user enters some text to the input (including copy-paste), we get and remove/replace all of the characters which are not numeric.

function filterNumber(input){
  input.value = input.value.replace(/\D*/g, '');
}
<input oninput="return filterNumber(this)" type="text" id="phone">

Upvotes: 0

Related Questions