Archie Archie - 5 months ago 60
Javascript Question

Simple PIN validation

Task:
ATM machines allow 4 or 6 digit PIN codes and PIN codes cannot contain anything but exactly 4 digits or exactly 6 digits.
If the function is passed a valid PIN string, return true, else return false.

My solution:

function validatePIN (pin) {
//return true or false
if (!isNaN(pin) && Number.isInteger(pin) && pin.toString().length == 4 || pin.toString().length == 6) {
return true
} else {
return false
}
}


The only bug I get is when I pass 4 digits as a string (
"1234"
) - it equals
false
.

Answer
function validatePIN (pin) {
  // return true or false
  if (typeof pin === "string" && !~pin.indexOf('.') && !isNaN(Number(pin)) && (pin.length === 4 || pin.length === 6)) { 
    return true; 
  } else { 
    return false; 
  }
}

EDIT:

Now only accepts a string, and "1234.0" fails.

EDIT2:

0000 and 000000 succeed, though maybe not the most elegant solution :)

EDIT3:

Added a shorter example, suggested by GingerPlusPlus.

function validatePIN (pin) {
    // return true or false
    return typeof pin === "string" && !~pin.indexOf('.') && !isNaN(Number(pin)) && (pin.length === 4 || pin.length === 6);
}
Comments