0

I use this code to validate the form of the username:

var nameRegex = /^(?=.{3,20}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$/;
var validUsername = usernameText.value.match(nameRegex);

if (validUsername == null) {
    //Username is not valid  
} else {
    //Username is valid
}

It works fine is Chrome, but when I test it in Safari, both iOS and MacOS I get this error message in the console: SyntaxError: Invalid regular expression: invalid group specifier name.

I'm pretty new to regular expressions and don't know how to modify the code to make it work in all browsers, or another solution to validate the username.

Peter
  • 1,848
  • 4
  • 26
  • 44
  • does the error go away if you remove `(?<![_.])` ? as per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Browser_compatibility lookbehind isn't supported on safari – Sundeep Aug 29 '20 at 10:25
  • also, you could use `test` method to get `true/false` instead of using `match` method and then checking for `null`, etc – Sundeep Aug 29 '20 at 10:25
  • https://stackoverflow.com/questions/641407/javascript-negative-lookbehind-equivalent has some alternate suggestions for lookbehind.. but I think you could use `(?!.*[_.]$)` at the start of the expression instead of `(?<![_.])` – Sundeep Aug 29 '20 at 10:29
  • https://caniuse.com/#feat=js-regexp-lookbehind – Toto Aug 29 '20 at 11:48

0 Answers0