javascript - 使用 JavaScript 验证 PIN - SyntaxError : Unexpected token )

标签 javascript regex

说明如下:ATM 机允许使用 4 或 6 位 PIN 码,并且 PIN 码只能包含 4 位或 6 位数字。如果函数传递了有效的 PIN 字符串,则返回 true,否则返回 false。

这是我的代码:

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

这是错误:

/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

我查看了 StackOverflow 条目:Regex validate PIN code JS

最佳答案

  • 您错过了第二个}
  • 对于逻辑“或”,您需要两个||
  • 在 javascript 中没有 True,只有 true

这应该是正确的代码:

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

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

你甚至可以像这样简化它:

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

  return regexPIN.test(pin);
}

关于javascript - 使用 JavaScript 验证 PIN - SyntaxError : Unexpected token ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52560839/

相关文章:

javascript - RailwayJS vs Geddy vs Express vs Socket.IO

javascript - Gulp bower 主失去了自己

javascript - 迁移到react-router v4 - 需要 router props 的子路由

javascript - promise 的正确解决方案

python - 如何在python中使用\K作为正则表达式?

regex - 正则表达式排除特定字符串

javascript - 你能 "accumulate" promise 导致 "then"链吗?

regex - ocaml 正则表达式的问题,基本模式不起作用

php - preg_match php 错误 - 找不到结束分隔符 '^'

regex - 递归查找和替换(某些文件除外)