验证器 (npm) 用户名​​验证

NG2*_*235 1 validation node.js npm

我正在使用 Node.js 构建一个 Web 应用程序。

我目前正在使用该validator包来验证输入。我想只允许使用字母数字字符,但也允许使用句点、下划线和连字符。(._-)

一些示例代码如下:

if (!validator.isEmpty(username)) {
    console.log('Username not provided');
} else if (!validator.isAlphanumeric(username)) {
    console.log('Username is not alphanumeric');
} else {
    console.log('Good Username!');
}
Run Code Online (Sandbox Code Playgroud)

我想在上面的代码中的某个地方检查句点、下划线和连字符,并允许它们通过该validator.isAlphanumeric方法。

谢谢你。

Gab*_*ile 6

您需要为此使用正则表达式。

if (!validator.matches(username, "^[a-zA-Z0-9_\.\-]*$")) {
  console.log('Username not valid');
} else {
  console.log('Good Username!');
}
Run Code Online (Sandbox Code Playgroud)

解释:

^ : start of string
[ : beginning of character group
a-z : any lowercase letter
A-Z : any uppercase letter
0-9 : any digit
_ : underscore
\.: Escaped character. Matches a dot
\-: Escaped character. Matches a  minus
] : end of character group
* : zero or more of the given characters
$ : end of string
Run Code Online (Sandbox Code Playgroud)

您可以在这里检查正确性:https : //regexr.com/4r65m