Reputation: 43
I need to validate if the url entered in the textbox is a valid domain by comparing it with a set of valid domains and return an alert if its not matching. Can you please help me with this ?
The URL should be of the format http://www..abc.com/cdef.. http://www..xyz.com etc..
I have tried using this regex:
regex = /((http|https):\/\/)(www.)?([a-zA-Z0-9]+).((abc.com)|(xyz.com)).*/
but its not yielding proper results. Hope this info helps.
Upvotes: 0
Views: 251
Reputation: 689
This is a basic programming exercise. You can use a put your urls in an array and then loop through them to check against what you entered.
Here's a jsfiddle of something I hack together quickly. Learn to write it yourself afterwards and you can hack together small programs to help you do mundane tasks.
var listOfUrl = [
'www.yahoo.com',
'www.google.com',
'www.bing.com'
//enter more url here...
];
for(var i = 0; i <= listOfUrl.length; i++) {
if(listOfUrl[i] === enteredUrl){
document.getElementById('result').innerHTML = 'there is a match';
return;
}
http://jsfiddle.net/henryw4k/5mogf06t/
Upvotes: 0
Reputation: 34189
You can do this using JavaScript URL
object and its host
property:
function isAllowed(urlString)
{
var allowed = ['example.com', 'stackoverflow.com', 'google.com'];
var urlObject = new URL(urlString);
return allowed.indexOf(urlObject.host) > -1;
}
console.log(isAllowed('http://example.com/path/?q=1')); // true
console.log(isAllowed('https://subdomain.example.com/')); // false
console.log(isAllowed('http://stacksnippets.net')); // false
if (!isAllowed(document.getElementById('yourTextbox').value))
{
alert('Domain is not allowed!');
}
Note that it may not work in all browsers.
Check the compatibility table in the given reference.
Upvotes: 1