I have written regex to validate URL which could be either like
example.com
www.example.com
All 4 are working
Now, if I am entering in a text like (www.example.com--thisisincorrect), it is allowing me to enter and save into db
The regex that I have used is:
http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?
and
([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?
Please help!
when creating a regex for strict matching, you must make it sure it begins with '^' and finishes with '$'. Otherwise, the regex will see if it finds a substring which matches.
However, using a regex to match an URL is error prone : better rely on existing frameworks doing it better (there are a lot of potential traps in url, like parameters, unkown domains, url containing ip instead of domain....)
This is to support both http, https as optional and validate blank space is not included in url.
Add
^
and$
This matches beginning of the string (
^
) and end ($
)You are Looking for this
Without Http:
With Http(s):
or
Best Regex:
I would like to share with you advanced version of @sach4all regexp query that check all links if they have correct superdomain in case that some links only fake a correct URL address.
The list of superdomains are collected in 1 January 2019 from http://data.iana.org/TLD/tlds-alpha-by-domain.txt