Skip to content Skip to sidebar Skip to footer

How To Allow Only A Certain Set Of Domains In Javascript And Throw An Alert If Its Not Matchin?

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 w

Solution 1:

You can do this using JavaScript URL object and its host property:

functionisAllowed(urlString)
{
    var allowed = ['example.com', 'stackoverflow.com', 'google.com'];
    var urlObject = newURL(urlString);

    return allowed.indexOf(urlObject.host) > -1;
}

console.log(isAllowed('http://example.com/path/?q=1')); // trueconsole.log(isAllowed('https://subdomain.example.com/')); // falseconsole.log(isAllowed('http://stacksnippets.net')); // falseif (!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.

Solution 2:

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/

Post a Comment for "How To Allow Only A Certain Set Of Domains In Javascript And Throw An Alert If Its Not Matchin?"