简体   繁体   中英

JavaScript - Allow only numbers from paste without using jQuery

I have this script that only allow numbers to be typed in and everything works great but I want to be able to paste only numbers if the user decides to use paste in an input.

The paste i'm referring to is mouse paste and keyboard paste . Paste in general. I tried to figure this out but I can not seem to find a way to do this.

Here is my code.

 //Prevent non numbers from keypress document.querySelector('#numbers-only').addEventListener('keypress',preventNonNumbersInInput); function preventNonNumbersInInput(event){ var characters = String.fromCharCode(event.which); if(!(/[0-9]/.test(characters))){ event.preventDefault(); } } //Prevent non numbers from being pasted only numbers can be pasted document.querySelector('#numbers-only').addEventListener('paste',pasteTest); function pasteTest(){ //??? } 
 <input type="text" id='numbers-only'> 

Here you go.

You can create a list of invalid chars to prevent on keydown ie paste.

Below is working code:

 var input = document.getElementById("numbers-only"); var invalidChars = [ "-", "+", "e", "." ]; input.addEventListener("input", function() { this.value = this.value.replace(/[e\\+\\-]/gi, ""); }); input.addEventListener("keydown", function(e) { if (invalidChars.includes(e.key) || e.which === 38 || e.which === 40) { e.preventDefault(); } }); 
 input[type="number"]::-webkit-outer-spin-button, input[type="number"]::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; } 
 <input type="number" id="numbers-only" /> 

Since it is an input you can easly change che input type to number. The web browser will then take care of allowing only numbers.

<input type="number" id='phone-number'>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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