2

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.

mj2008
  • 6,647
  • 2
  • 38
  • 56

3 Answers3

4

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
  • 15,076
  • 6
  • 55
  • 70
3

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.

Community
  • 1
  • 1
Scott W
  • 9,742
  • 2
  • 38
  • 53
  • 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 Jan 27 '09 at 16:40
  • 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 Jan 27 '09 at 17:23
  • 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 Jan 27 '09 at 22:04
1

Perhaps some of the suggestions here might help.

Community
  • 1
  • 1
Ondrej Kelle
  • 36,941
  • 2
  • 65
  • 128
  • This may be a good option - break the URL into bits that exist, and then reconstitute with any missing parts. – mj2008 Jan 28 '09 at 09:03