0

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.

Trident
  • 810
  • 9
  • 20

2 Answers2

1

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.

Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
  • how can I validate the URL, is there any way? – Trident Jul 31 '15 at 16:10
  • [A quick search](http://stackoverflow.com/questions/8660209/how-to-validate-url) shows some simple ways. – Mike Cluck Jul 31 '15 at 16:11
  • the url is valid only, I just want to check the edge case, when the webpage might be down, I think regex may not help in this situation, any comments..? – Trident Jul 31 '15 at 16:14
  • @Krish Which one is it? Is the URL invalid, is the domain invalid (`groogle.com` instead of `google.com`), or the site is down (getting a 404 error)? – Mike Cluck Jul 31 '15 at 16:26
  • it includes may the URL's formats like, iPhone considers `tel://1234567890` also a valid url, but lets say if the url is tele://1234567890, it is a wrong url, so how do i catch this – Trident Jul 31 '15 at 16:29
  • Regex will catch that. You just need to adjust your regex to look for `tel` in addition to `http` and `https`. It's a trivial addition. – Mike Cluck Jul 31 '15 at 16:30
  • yes, but there can be so many such formats, so we can not include all of them in RegEx. iPhone has lot of urls for calendar, notes, mail.. etc.. – Trident Jul 31 '15 at 16:32
  • @Krish You can include them all in a regex. Nothing is stopping you. You have to store what a valid protocol is somewhere. Other than that, you could attempt to split on `://` then check if the first section matches your allowed set of protocols. – Mike Cluck Jul 31 '15 at 16:35
  • it is impossible to add them all as we do not know all the formats available – Trident Jul 31 '15 at 16:36
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/84827/discussion-between-mike-c-and-krish). – Mike Cluck Jul 31 '15 at 16:36
1

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.