Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validator (npm) Username Validation

I am building a web app with Node.js.

I am currently using the validator package to validate inputs. I would like to have only alphanumeric characters allowed, but with the period, underscore and hyphen allowed also. (. _ -)

Some sample code is below:

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!');
}

I would like to have somewhere in the code above that checks for periods, underscores, and hyphens and allows them to get through the validator.isAlphanumeric method.

Thank you.

like image 986
NG235 Avatar asked Jun 18 '26 02:06

NG235


1 Answers

You need to use a regex for that.

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

Explanation:

^ : 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

You can check the correctness here: https://regexr.com/4r65m

like image 88
Gabriel Vasile Avatar answered Jun 20 '26 15:06

Gabriel Vasile



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!