Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript URL validation regex

I had the following url validation regex:

/(ftp|https?)://[^ "]+$/

This is from the ref: Regular expression for URL validation (in JavaScript)

This works fine including cases like http://localhost:8080, but it also validates the below ones that i dont want. The above regex should not pass the below urls

 1. http://www.example..com
 2. http://.com
 3. http://.
 4. http://www.example. 

Kindly help as am a noob in regex

Second question, though not related to the question but regex is, when i validate null and undefined against the regex /^[a-z]+$/i i get true. Is this the default behavior or am i missing something over here?

like image 470
hellojava Avatar asked Aug 21 '13 17:08

hellojava


1 Answers

Try this

function is_valid_url(url)
{
     return url.match(/^(ht|f)tps?:\/\/[a-z0-9-\.]+\.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`]+)?$/);
}

Call the is_valid_url(YOUR_WEBSITE_URL) function everywhere which you want to website validate.

like image 118
Chinmay235 Avatar answered Sep 30 '22 13:09

Chinmay235