javascript, allow only numbers to be entered in form

created at 10-19-2021 views: 5

code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://vuejs.org/js/vue.min.js"></script>
</head>
<body>
    <input type="text" onkeyup="this.value=this.value.replace(/[^0-9]+/g,'')"> <!-- No Pinyin mixing-->
    <script>
        document.querySelector("input").addEventListener("keydown", function(event){
            if(event.key in ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']){}  // allow number
            else if(event.keyCode == 8){}  // allow delete
            else
                event.preventDefault();
        })
    </script>
</body>
</html>

Use: Save this code to a file, then import it, add the validate class name to the form that needs to be validated, and then import it from the end:

document.querySelectorAll('.validate').forEach((v,i,arr)=>{
     v.addEventListener('keydown', event=>{
         console.log(event);
         if(event.key in ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']){} // Allow numbers
         else if(event.keyCode == 8){} // Allow deletion
         else
             event.preventDefault();
     })
     v.onkeyup = function(){
         v.value = v.value.replace(/[^0-9]+/g,'');
     }
})

This class name can also be changed and can be customized. If you allow floating-point numbers or other types to change the regular expression.

created at:10-19-2021
edited at: 10-19-2021: