How to create a strict 4-digit PIN input in plain JavaScript? <p>I'm trying to create a PIN input, wherein the user may only use 4 digits.</p> <p>In my code, I have managed to exclude A-Z and any other keys like curly braces, colons and so on, but I have faced some trouble with excluding the special characters (shift + 0-9).</p> <p>Regarding the length, I have successfully set it to 4, but if 4 is reached and one wants to delete it doesn't go past 3.</p> <p>My code:</p> <pre><code>var pin = document.forms.RegForm.pin; pin.onkeydown = function(key) { var allowedkeys = [], auxkeys = [8, 13, 17, 18, 46], specChars = "!@#$%^&amp;*()", keypressed = String.fromCharCode(key.which); allowedkeys.push(auxkeys); for (var i = 37; i &lt; 41; i++) allowedkeys.push(i); for (var i = 48; i &lt; 58; i++) allowedkeys.push(i); for (var i = 96; i &lt; 106; i++) allowedkeys.push(i); if (this.value.length &lt;= 3) { if (specChars.indexOf(keypressed) !== -1 || (key.which &lt; 48 || key.which &gt; 57) &amp;&amp; (key.which &lt; 96 || key.which &gt; 105)) key.preventDefault(); } else { if (auxkeys.indexOf(key.which) === -1) return false; } }; </code></pre> <p>I know the length can easily be done with maxlength = "4" in HTML, but for the purpose of getting to know JavaScript better, I would prefer an 'in JavaScript' solution.</p> <p>Should you provide an answer or a link to a similar question, if there is one, I would appreciate it. Fiddle: <a href="https://jsfiddle.net/qn968nhm/1/" rel="nofollow">https://jsfiddle.net/qn968nhm/1/</a></p>