0

i have this regex code

/^(https?:\/\/+[\w\-]+\.[\w\-]+)/i

it works but there is a problem you NEED http:// in the url for it to validate, and what i am making, the user will not want to add http:// to the url they want to just have example.com, if its possible i need it to work weather it has http:// or not
i don't know how to make my own regex, and ive searched but cannot find a one that does what i need, unless im just not looking in the right place. (Google :P)

Cody
  • 1,281
  • 2
  • 10
  • 12
  • possible duplicate of [PHP validation/regex for URL](http://stackoverflow.com/questions/206059/php-validation-regex-for-url) – kennytm Jun 21 '11 at 12:16

4 Answers4

4

Don't bother with regex. Use parse_url function.

Purple Coder
  • 319
  • 1
  • 13
2

You can just make it optional

/^((?:https?:\/\/+)?[\w\-]+\.[\w\-]+)/i

The (?:) around the part you don't want to have is a non capturing group, the ? afterwards makes it optional.

I'm not sure what the + after the second slash is good for, it says at least one of the preceding character. That means it allows also stuff like http://////////.

I hope you are aware, that this regex is far from matching valid URLs.

For example it will match stuff like

http://////////------------.-

or at least

http://N.O
          ^ after this position you can write what you want and it will match valid.

Here on Regexr you can see what your regex is matching.

See Purple Coder's answer for a probably better solution.

stema
  • 90,351
  • 20
  • 107
  • 135
0

/^((https?:\/\/+)?[\w-]+.[\w-]+)/i

Eric Mason
  • 715
  • 7
  • 17
0

I'm using this :

// Validate that the string contains at least a dot .

var filterWebsite =  /^([a-zA-Z0-9:_\.\-/])+\.([a-zA-Z0-9_\.\-/])+$/;
Tarek
  • 3,810
  • 3
  • 36
  • 62