-1

I'm trying to validate a field called "role" where the pattern's type is only names like this: super_user, computer_group. But not this: "admin_area_" or "Admin_area??", "ADMIN_". Only lowercase letters and underscore between those letters, never on final. This is what i tried until now:

/^[a-z]+(_*[a-z]+)*$/ and /^[a-z_]*$/

But for some reason, when the user types "??" or any other character my validation is still allowing those characters.

NOTE: my inputs are from quasar framework where I validate that in :rules

dale landry
  • 7,831
  • 2
  • 16
  • 28
Joe RR
  • 262
  • 3
  • 22
  • 1
    The first regex looks like it covers all your test cases pretty well https://regex101.com/r/Ip5LNf/1 – Taxel Jan 22 '21 at 16:11
  • hmmm weird... well, i think i not tested it very well – Joe RR Jan 22 '21 at 16:16
  • So `super_user_person` is valid or invalid? Ditto for `super__user` and `username` – MonkeyZeus Jan 22 '21 at 16:18
  • @Taxel `_*` is a very inefficient choice – MonkeyZeus Jan 22 '21 at 16:21
  • @MonkeyZeus I agree, but that was not the question. I would suggest turning `_*` (zero or multiple underscores) into `_?` (zero or one underscore) and also turn the capturing into a non-capture group, so all in all I would suggest `/^[a-z]+(?:_?[a-z]+)*$/` – Taxel Jan 22 '21 at 16:29
  • @Taxel That's just as bad. Switch to PHP or Python at regex101 and look at the "steps" in the upper right. Now try `^[a-z]+(?:_[a-z]+)*$` and you will see a 10 fold difference – MonkeyZeus Jan 22 '21 at 16:35

2 Answers2

1

your first regex is working well still you can try this one. it won't allow without underscore.

^[a-z]+_[a-z]+$
Flash Noob
  • 352
  • 3
  • 7
0

The answer by Flash Noob, validates ?? too. Instead, you can use:

^[a-z]+(?:_{0,2}[a-z]+)*$
Adriaan
  • 17,741
  • 7
  • 42
  • 75
Dhanashri P
  • 111
  • 5
  • `The answer by Flash Noob, validates ??` please clarify. Since the other answer accepts a minimum of 3 characters (and won’t accept any literal `?`) - I think there’s a misunderstanding here. Note also this regex [doesn’t do what is asked](https://regex101.com/r/6Q9nlT/1) and is almost identical to a regex discussed in the question comments. – AD7six Feb 07 '23 at 07:31