-2

I want a Regex for my mongoose schema to test if a username contains only letters, numbers and underscore, dash or dot. What I got so far is

/[a-zA-Z0-9-_.]/

but somehow it lets pass everything.

Conspicuous Compiler
  • 6,403
  • 1
  • 40
  • 52
Gabo
  • 1
  • 1
  • 2
    What does it match when it shouldn't? Can you give some example inputs, expected output and the actual output? – Sweeper Dec 30 '17 at 00:47

3 Answers3

3

Your regex is set to match a string if it contains ANY of the contained characters, but it doesn't make sure that the string is composed entirely of those characters.

For example, /[a-zA-Z0-9-_.]/.test("a&") returns true, because the string contains the letter a, regardless of the fact that it also includes &.

To make sure all characters are one of your desired characters, use a regex that matches the beginning of the string ^, then your desired characters followed by a quantifier + (a plus means one or more of the previous set, a * would mean zero or more), then end of string $. So:

const reg = /^[a-zA-Z0-9-_.]+$/

console.log(reg.test("")) // false
console.log(reg.test("I-am_valid.")) // true
console.log(reg.test("I-am_not&")) // false
CRice
  • 29,968
  • 4
  • 57
  • 70
1

Try like this with start(^) and end($),

^[a-zA-Z0-9-_.]+$

enter image description here

See demo : https://regex101.com/r/6v0nNT/3

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
  • Tiny nitpick, it turns out that when a `.` appears in a character group (inside `[]`, it is already interpreted literally and there's no need to escape it. – CRice Dec 30 '17 at 01:02
-1

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

This regex should work.

^ matches at the beginning of the string. $ matches at the end of the string. This means it checks for the entire string.

The * allows it to match any number of characters or sequences of characters. This is required to match the entire password.

Now the parentheses are required for this as there is a | (or) used here. The first stretch was something you already included, and it is for capital/lowercase letters, and numbers. The second area of brackets are used for the other characters. The . must be escaped with a backslash, as it is a reserved character in regex, used for denoting that something can be any character.

Milesman34
  • 177
  • 1
  • 6
  • You don't need to escape dots when they are part of a character class. https://stackoverflow.com/questions/19976018/does-a-dot-have-to-be-escaped-in-a-character-class-square-brackets-of-a-regula – Conspicuous Compiler Mar 28 '19 at 17:25