0

I have this regex code

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

It works for full URLs, but you NEED http:// in the url for it to validate.

I am seeking a way to validate a URL where the protocol is optional.

The user won't want to add http:// to the URL, they want to just have example.com.

If it's possible, I need it to work whether it has http:// or not.

How do I do this?

0

4 Answers 4

4

Don't bother with regex. Use parse_url function.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

0

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

Comments

0

I'm using this :

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

var filterWebsite =  /^([a-zA-Z0-9:_\.\-/])+\.([a-zA-Z0-9_\.\-/])+$/;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.