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
Check this - http://docs.jquery.com/Plugins/Validation/Methods/url
$("#myform").validate({
rules: {
field: {
required: true,
url: true
}
}
});
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");
}
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>
your pattern is defined as
^(http:\/\/|someting else
thus any-urls begin with "http://" would be validated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With