How to validate usernames using matches(regex)?

久未见 提交于 2019-12-10 10:45:58

问题


I'm trying to put the following expression into the matches function but I guess errors when trying to compile the rules.

 ^[a-zA-Z](([\._\-][a-zA-Z0-9])|[a-zA-Z0-9])*[a-z0-9]$

.validate rule looks as follows:

".validate": "newData.val() === auth.uid         
&& newData.val().matches(^(?=.{5,10}$)(?!.*[._-]{2})[a-z][a-z0-9._-]*[a-z0-9]$)" 

I get:

" Invalid escape: '\.'"

回答1:


It appears you cannot use lookarounds in Firebase, so your pattern and the whole approach should be adjusted to account for that.

Your current regex requires a string length from 5 to 10 symbols, and disallows 2 consecutive symbols ., _ and -. The first condition should be checked outside the regex with some code like newData.val().length >= 5 && newData.val().length <= 10 and the second one just requires re-grouping and re-quantifying:

.matches(/^[a-z][a-z0-9]*([._-][a-z0-9]+)*$/)

See the regex demo.

Details:

  • ^ - start of string
  • [a-z] - a lowercase letter (if you add /i at the end, it will be case sensitive)
  • [a-z0-9]* - zero or more a-z and 0-9 symbols
  • ([._-][a-z0-9]+)* - a ., _ or - followed with one or more (this requires [a-z0-9] to be at the end if there is ., _ or - in the string) characters from 0-9 and a-z ranges
  • $ - the end of string anchor.

Note you do not need to escape the characters inside the character class as the . and _ are not special chars inside it, and the - at the end or start of the bracket expression (character class) is a literal hyphen.



来源:https://stackoverflow.com/questions/39503825/how-to-validate-usernames-using-matchesregex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!