Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple PIN validation

Tags:

javascript

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.

like image 342
Archie Avatar asked Jul 03 '16 08:07

Archie


People also ask

How do I validate a pin in Python?

function validatePIN (pin) { return typeof pin === 'string' && // verify that the pin is a string Number.isInteger (+pin) && // make sure that the string is an integer when converted into a number [4, 6].includes (pin.length) // only accepts 4 and 6 character pins } Show activity on this post.

How to validate Pin code of India using regex?

Create a regular expression to validate pin code of india as mentioned below: regex = "^[1-9]{1}[0-9]{2}\\s{0, 1}[0-9]{3}$"; Where: ^ represents the starting of the number. [1-9]{1} represents the starting digit in the pin code ranging from 1 to 9. [0-9]{2} represents the next two digits in the pin code ranging from 0 to 9.

What are the conditions for a PIN code to be valid?

First digit of the pin code must be from 1 to 9. Next five digits of the pin code may range from 0 to 9. It should allow only one white space, but after three digits, although this is optional. The given number satisfies all the above mentioned conditions. The given number satisfies all the above mentioned conditions.

How many digits can a PIN code have?

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.


Video Answer


1 Answers

function validatePIN (pin) {
  return typeof pin === 'string' && // verify that the pin is a string
    Number.isInteger(+pin) && // make sure that the string is an integer when converted into a number
    [4, 6].includes(pin.length) // only accepts 4 and 6 character pins
}
like image 56
b00t Avatar answered Oct 07 '22 16:10

b00t