Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Validation to validate URL

I am trying to validate URL in jQuery regular expression using below code. It is working fine with http://www and https://www

var myVariable = "http://www.example.com/2013/05/test-page-url-512-518.html";

if(/^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/|www\.)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/.test(myVariable)){
    alert("valid url");
} else {
    alert("invalid url");
}

Edit:-

Above code work perfectly to validate URL. That time my requirement was only to validate http://www and https://www

like image 552
Roopendra Avatar asked May 14 '13 07:05

Roopendra


4 Answers

Check this - http://docs.jquery.com/Plugins/Validation/Methods/url

$("#myform").validate({
  rules: {
    field: {
      required: true,
      url: true
    }
  }
});
like image 120
ChamingaD Avatar answered Sep 19 '22 13:09

ChamingaD


You can change your Regex, actually there is a repetition of item i.e. http:\/\/|https:\/\/|www\.

This code will work out for you:

var myVariable = "http://www.example.com/2013/05/test-page-url-512-518.html";

if(/^(http:\/\/www\.|https:\/\/www\.)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/.test(myVariable)){
    alert("valid url");
} else {
    alert("invalid url");
}
like image 27
Santosh Panda Avatar answered Sep 22 '22 13:09

Santosh Panda


You want to validate your URL:

Please pass the URL in this function then this will give you true OR false.

The Function :

<script>
function isUrl(s) {
    var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
    return regexp.test(s);
}

isUrl(yourURL);
</script>
like image 45
Vishnu Sharma Avatar answered Sep 22 '22 13:09

Vishnu Sharma


your pattern is defined as

^(http:\/\/|someting else

thus any-urls begin with "http://" would be validated.

like image 30
Chu Ya'an Xiaonan Avatar answered Sep 22 '22 13:09

Chu Ya'an Xiaonan