Trident
Trident

Reputation: 832

JavaScript : Prevent showing alert when the url being opened is invalid

I have a requirement where I have to open a URL from html page. But, before I open the URL I cannot determine if the URL is a valid or not, so when I try to open a invalid url, the webpage throws an alert saying "Safari cannot open the page because the address is invalid.".

I understand it is designed for a reason, but is there anyway to prevent showing this alert, when the url is not a valid one.

EDIT : The url is in valid format only, but the website domain is wrong. I think, regex will not help in this case.

Upvotes: 0

Views: 590

Answers (2)

Pratik Patel
Pratik Patel

Reputation: 92

Use a regular expression to validate the url syntax before passing it to safari. For example:

^(http(?:s)?\:\/\/[a-zA-Z0-9]+(?:(?:\.|\-)[a-zA-Z0-9]+)+(?:\:\d+)?(?:\/[\w\-]+)*(?:\/?|\/\w+\.[a-zA-Z]{2,4}(?:\?[\w]+\=[\w\-]+)?)?(?:\&[\w]+\=[\w\-]+)*)$

If this does not work for you, you can find many other url validation regular expressions to validate your URL.

Upvotes: 1

Mike Cluck
Mike Cluck

Reputation: 32511

You can't prevent Safari from presenting that alert when you attempt to access an invalid URL. Perhaps you should verify that it is a valid URL before attempting to access it.

Upvotes: 1

Related Questions