Reputation: 23
I am trying to make a function to validate url regular expression, and add "http://" if it's missing at the same time. I am quite new to Javascript and coding, and most part of the below code is what I have followed a Youtube tutorial.
But I wanted to add a function to prepend "http://" when it's missing, since with the current regex, both "www.google.com" and "http://www.google.com" is valid. The problem with this is when I actually click to visit the website, the ones saved without "http://" at start, doesn't go to the site.
function validateForm(siteName, siteUrl) {
if(!siteName || !siteUrl) {
alert('Please fill in the form');
return false;
}
var expression = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
var result = siteUrl.search(new RegExp(/^http:\/\//i));
if(!siteUrl.match(regex)) {
alert('Please use a valid URL');
return false;
}
else if(siteUrl.match(regex) && !result) {
siteUrl = "http://" + siteUrl
return true;
}
else {
return true;
}
}
Upvotes: 1
Views: 384
Reputation: 65806
You can use the .indexOf()
string method to determine if http://
is at the beginning of the string. However, you may run into problems prepending http://
if the URL requires https://
.
else if(siteUrl.match(regex) && !result) {
// Check to see if the string starts with "http://"
// indexOf() returns the index position of the supplied
// string argument within the string.
if(siteUrl.indexOf("http://") !== 0){
siteUrl = "http://" + siteUrl
}
return true;
}
Also (as @m_callens points out in the comments below), your siteUrl
variable is a function argument, so you won't be able to access it from outside of the function. Instead you should not pass it into the function at all and just have it declared in a higher scope:
var siteUrl = // Code that initializes the variable
function validateForm(siteName) {
if(!siteName || !siteUrl) {
alert('Please fill in the form');
return false;
}
var expression = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
var result = siteUrl.search(new RegExp(/^http:\/\//i));
if(!siteUrl.match(regex)) {
alert('Please use a valid URL');
return false;
}
else if(siteUrl.match(regex) && !result) {
// Check to see if the string starts with "http://"
// indexOf() returns the index position of the supplied
// string argument within the string.
if(siteUrl.indexOf("http://") !== 0){
siteUrl = "http://" + siteUrl
}
}
else {
return true;
}
}
Upvotes: 2