Angel Politis Angel Politis - 6 months ago 21
HTML Question

How to create a strict 4-digit PIN input in plain Javascript? [SOLVED]

I am trying to create a PIN input, wherein the user may only use 4 digits.

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).

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.

My code:

var pin = document.forms.RegForm.pin;

pin.onkeydown = function(key) {
var allowedkeys = [];
var auxkeys = [8, 13, 17, 18, 46];
var specChars = "!@#$%^&*()";
var keypressed = String.fromCharCode(key.which);

allowedkeys.push(auxkeys);
for (var i = 37; i < 41; i++) {allowedkeys.push(i)};
for (var i = 48; i < 58; i++) {allowedkeys.push(i)};
for (var i = 96; i < 106; i++) {allowedkeys.push(i)};

if (this.value.length <= 3) {
if ((allowedkeys.indexOf(key.which) !== -1) ||
(key.which == 65 && key.ctrlKey === true) ||
(key.which >= 35 && key.which <= 36)) {
return;
}
else if (specChars.indexOf(keypressed) !== -1 ||
(key.which < 48 || key.which > 57) &&
(key.which < 96 || key.which > 105)) {
key.preventDefault();
}
}
else {
if (auxkeys.indexOf(key.which) === -1) {
return false;
}
}
};


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.

Should you provide an answer or a link to a similar question, if there is one, I would appreciate it. Fiddle: https://jsfiddle.net/qn968nhm/1/

[ANSWER]:

pin.onkeypress = function (e) {
if (this.value.length <= 3) {
// Return only numbers
return e.which >= 48 && e.which <= 57; // @a.j.'s answer
}
else {
// If length is 4 disable input
return false;
}
};

Answer

You can ensure that they only enter digits in this way (so as to make the JS as simple as possible).

pin.onkeypress = function (e) {
   return e.charCode >= 48 && e.charCode <= 57;
};