Home > Software design >  Firebase Realtime Database security rules regular expression: Normal Javastring regex doesn't g
Firebase Realtime Database security rules regular expression: Normal Javastring regex doesn't g

Time:11-22

I have this regex: /^(?=[^A-Za-z]*([A-Za-z][^A-Za-z]*){6}$)\w $/

But it doesn't get accepted in .validate's matches(). Shows invalid character and other such errors.

"$username": {
        // here
        ".validate": "$username.matches(/^(?=[^A-Za-z]*([A-Za-z][^A-Za-z]*){6}$)\w $/)",
        ".write": "(auth.uid != null && newData.val() === auth.uid) || (auth != null && !newData.exists())"
}

What all changes do I need to make to expression to make it accept in rules?

CodePudding user response:

Looking at this page Firebase Security Rules Regular Expressions lookarounds and non capture groups do not seem to be supported.

You might write the pattern without any lookarounds, repeat a capture group 6 times and only use \w as that is only allowed to match:

^\w*([A-Za-z]\w*){6}$

The pattern matches:

  • ^ Start of string
  • \w* Match optional leading word chars
  • ([A-Za-z]\w*){6} Match 6 times a char A-Z a-z followed by optional trailing word chars
  • $ End of string

See a regex demo.

The final working command according to the comments:

".validate": "$username.matches(/^\\w*([A-Za-z]\\w*){6,}$/)",
  • Related