0

These are the instructions: 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.

This is my code:

function validatePIN (pin) {
  //return true or false
  let regexPIN4 = /^\d{4}$/;
  let regexPIN6 = /^\d{6}$/;
  
  if (regexPIN4.test(pin)|regexPIN6.test(pin)){
      return True;
};

This is the error:

/home/codewarrior/index.js:47
});
 ^

SyntaxError: Unexpected token )
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:616:28)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at [eval]:1:1

I reviewed StackOverflow entry: Regex validate PIN code JS

Community
  • 1
  • 1
LearningD3
  • 151
  • 1
  • 16

3 Answers3

3
  • you were missing second }
  • for logical OR you need two ||.
  • in javascript there is no True, only true

this should be the right code:

function validatePIN (pin) {
  let regexPIN4 = /^\d{4}$/;
  let regexPIN6 = /^\d{6}$/;

  return regexPIN4.test(pin) || regexPIN6.test(pin);
}

You can even simplify it like this:

function validatePIN (pin) {
  let regexPIN = /^(\d{4}|\d{6})$/;

  return regexPIN.test(pin);
}
1

Apart from your syntax mistakes, here's a demo to get your task done with only one regex that allows only 4 or 6 digits.

function checkPin(pin) {
  // regex to check for pins with 4 or 6 digits
  return /^\d{4}(\d{2})?$/.test(pin);
}

console.log(checkPin(1234)); // true
console.log(checkPin(123456)); // true
console.log(checkPin(12)); // false - not exactly 4 or 6 digits
console.log(checkPin('12h34')); // false - a non-digit character

About your mistakes:

  • the logical OR operator in JavaScript is written like: || not |.
  • You missed an } to close the if statement.
  • And it's true not True, keep this in mind, JavaScript is case-sensitive.

Hope I pushed you further.

Nick
  • 138,499
  • 22
  • 57
  • 95
ThS
  • 4,597
  • 2
  • 15
  • 27
0

8ADBO

function validatePIN (pin) {
  //return true or false
  let regexPIN4 = /^\d{4}$/;
  let regexPIN6 = /^\d{6}$/;
  
  if (regexPIN4.test(pin)|regexPIN6.test(pin)){
      return True;
};
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 08 '23 at 21:12