tags:

views:

410

answers:

3

I need a user to be able to enter a URL, and would like to make sure it is as wholesome as possible. Things like checking that there is http:// at the front, no double-dots, perhaps valid TLD, trailing slash (I have to add the final page).

I figure this is such a common requirement that it must exist already. Suggestions?

[edit:] To be clear, this is a run-time requirement in a Windows Service. The aim is to get the best from the URL read from the configuration, rather than validate what the user typed in. In essence, if I can adjust the URL and make it work, then that is what I'd like to do. The download will be a specific file, so if it all goes wrong it won't get the wrong thing from another server by mistake.

+3  A: 

Have you had a look at "What is the best regular expression to check if a string is a valid URL"? It is not Delphi specific, but might get you started.

Scott W
Hmm, an interesting idea, thanks, but I'd rather "auto-correct" the URL instead of just validating it. But validating it on entry might be good to do too.
mj2008
Instead of auto-correcting, you can simply show a visual sign that the entered URL is not correct. e.g. disable the OK button or set the edit background to red.
Bruce McGee
But before you can autocorrect, you need to know what to correct, so you need some kind of validation. A nice regex will tell you if the protocol is missing, or if it ends with a slash. Use capturegroups - if they're empty - you need to add what's missing.
Vegar
+1  A: 

Perhaps some of the suggestions here might help.

TOndrej
This may be a good option - break the URL into bits that exist, and then reconstitute with any missing parts.
mj2008
+3  A: 

How about using the PathIsURL function in the Windows API?

Update: This is already wrapped in the Delphi RTL in the ShLwApi unit.

Bruce McGee