2

I want the regular expression to validate the URL with below condition,

  1. It should start with http or https
  2. It should end with the valid domain. Ex: .com or .in but after the . can have any string. Specially, check whether the . is there and there is a string following the ..

Valid URL: http://www.cnn.com

Invalid URLS:

htt://www.yahoo.com
http://www.yahoo.
http://www.yahoo

I have compose the regular expression as below.

/^(http|https):\/\/[-a-zA-Z0-9+&@#/%?=~_|!:,;]+([\-\.]{1}[-a-zA-Z0-9+&@#/%?=~_|]+)*\.[a-zA-Z]{2,5}(:[0-9]{1,5})?(\/.*)?$/

It worked fine for most of the scenarios.

But if I enter http://www.yahoo didn't validate correctly, but If I enter http://www.google it throws the validation error.

Can anybody please help me to resolve this issue?

Mr_Green
  • 40,727
  • 45
  • 159
  • 271
Java-Seekar
  • 1,720
  • 5
  • 30
  • 52

2 Answers2

2

Try this:

^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$
Yash Thakur
  • 1,172
  • 7
  • 14
0

You can use the following reg exp to match the urls

^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$

Check it here

https://www.regex101.com/r/jU7iT2/1

Rajeshwar
  • 2,290
  • 4
  • 31
  • 41