0

I have the following Regex:

var legal = /[a-zA-Z0-9\._\-]+/;

Which is supposed to define that the only valid strings are the ones made up of those characters inside [], repeated a positive number of times.

And so, the following works fine:

legal.test("a"); // => true
legal.test("/"); // => false

However, this does not work fine:

legal.test("a/"); // => true

It should be false. I tried putting a $ at the end of the ReGeX to signify end of line, and it helps, but not always:

var legal2 = /[a-zA-Z0-9\._\-]+$/;

legal2.test("a"); // => true
legal2.test("a/"); // => false
legal2.test("a/a"); // => true

The last one should be false, so the $ in the end doesn't always help.

What do I need to do to my Regex to make it act like a "template" for which strings to be validated?

Liam
  • 27,717
  • 28
  • 128
  • 190
David Gomes
  • 5,644
  • 16
  • 60
  • 103
  • 6
    You were already half-way there. `/^[a-zA-Z0-9\._\-]+$/` (In other words - why only anchor it to the end?) – Tomalak Aug 22 '16 at 12:44
  • @Tomalak, [this should be an answer](http://meta.stackexchange.com/a/117268/217110) – Liam Aug 22 '16 at 12:45

1 Answers1

4

You need to indicate the start of the string matching by a caret (^) in front:

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

This will now match only the strings containing only the allowed characters.

Your pattern [a-zA-Z0-9\._\-]+$ was matching the last a of a/a because you did not mention strictly where to start matching from but you did impose the end condition with $.

heemayl
  • 39,294
  • 7
  • 70
  • 76