tommyd456 tommyd456 - 7 months ago 16
Node.js Question

Using regex in Nodejs stopping flow

I'm experimenting with a regex from another question: Regex which accepts alphanumerics only, except for one hyphen in the middle

I have this code as part of my validation of a username:

var re = /^(?:[a-z0-9]{6,20}|(?=.{10,21}$)[a-z0-9]+-[a-z0-9]+)$/i;
var found = username.match(re).length;

but the flow stops here and won't continue past this point if the username is invalid. I need to be able to ask:

if(username fails regex) {
send error back to client


The problem with str.match(regex) is that it will return null if no match is found, consider this:

console.log('hello'.match(/world/)); // null

And reading .length from null will throw a TypeError.

You should try using regex.test(str) which will return a boolean:

var re = /^(?:[a-z0-9]{6,20}|(?=.{10,21}$)[a-z0-9]+-[a-z0-9]+)$/i;
var found = re.test(username); // true or false