Ad

How To Design A Regex In Firebase?

I can't work out why my regex is matching things it shouldn't when used on Firebase to validate usernames.

I've tried reading other posts like How to validate usernames using matches(regex)? but I still can't figure out what I'm doing wrong.

The regex I'm using is:

/^\\S+(\\s\\S+)*$/

Which is part of the rules I've defined here:

{
  "rules": {
    "users": {
      "$uid": {
        ".read": "auth != null",
        ".write": "$uid === auth.uid",
        ".validate": "newData.hasChildren(['username'])",
        "username": {
          ".validate": "newData.isString() && newData.val().length > 0 && newData.val().length < 21 && newData.val().matches(/^\\S+(\\s\\S+)*$/)"
        }
      }
    }
  }
}

I want to be able to match strings which don't start or end with a space character, and don't have any consecutive space characters.

Excluding the quotes, I expect something like "this is a username" to match and " hello world" to fail, but they both pass when I test them using the simulator on Firebase.

Firebase simulator output:

enter image description here

Ad

Answer

I've never used \S before, so had to look up what it does. But it indeed seems to be causing problems here. I'm not sure why, but it seems to include space characters in my quick testing, although interestingly enough tabs are not matched by \S.

You might want to try with \w, which worked for me and is very similar. Or you can invert \\s yourself with newData.val().matches(/^[^\\s].*$/), which is equivalent to what you're trying.

In that last one, I replaced (\\s\\S+)* by a much simpler .*, which should be equivalent.

Ad
source: stackoverflow.com
Ad