Javascript regex that can only contain letters, numbers, dashes and must contain a dot

I am really bad at Regex but in my JavaScript app I am trying to validate a form item, the value of the form item can only contain letters, numbers, dashes and at least one dot.

So the following would be valid:

hello.world

microsoft.com

So far I came up with this (.+)[a-zA-Z0-9.-]\.[a-zA-Z0-9.-]+$ but it doesn’t work as I can add spaces. What can I do to make my Regex work? Also can I prevent the dot being the first character?

21 thoughts on “Javascript regex that can only contain letters, numbers, dashes and must contain a dot”

  1. I think you can achieve this with the following

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

    ^[^.] is no starting dots

    [a-zA-Z0-9.-] is all characters lowercase, uppercase and digits including dot and hyphens. Credit to Wiktor & Peter for leading me to this

    $ makes sure it’s the end of the string, so it won’t match on a partial like "hello world"

    Example here: https://regex101.com/r/BXHmwh/1

    Reply

Leave a Comment