1

I have a form that users enters there website. Problem is some users put their email address in which I do not want. I want a way to check if the url is well structured. e.g. no @, must have a root domain. www subdomains are optional. I am unable to find this anywhere.

I have tried this code

if (!Uri.TryCreate("http://" + websiteurl, UriKind.Absolute, out uri) || null == uri)

returning false on error but my problem is that it still validates without a root domain e.g. I can put in

http://websitename 

and validates fine which I do not want. It does return false when I have put in

http://websitename@. 

Is there a way I can overcome this problem? also I added

http:// in the passthrough value because the url never validates.

James Andrew Smith
  • 1,516
  • 2
  • 23
  • 43

4 Answers4

5

You can use:

Uri.IsWellFormedUriString(inputUrl, UriKind.RelativeOrAbsolute)
Anujith
  • 9,370
  • 6
  • 33
  • 48
Pete
  • 6,585
  • 5
  • 43
  • 69
1

Depending on your performance needs, maybe issuing a quick HttpWebRequest for the website url they give and verifying that you get back a success response might be a good option.

Eric Petroelje
  • 59,820
  • 9
  • 127
  • 177
0

You could try with a regular expression.

Oscar
  • 13,594
  • 8
  • 47
  • 75
  • I think regular expression might cause more problems. Maybe we need a function / method that checks for specific domains e.g. .com /.net and a regex only allowing alphanumeric values and characters such as - . ? = – James Andrew Smith Dec 18 '12 at 09:08
0

Uri.IsWellFormattedUriString won't solve the problem here, which includes the ability to distinguish a valid Url from an email address. Both are well formatted Uris.

Use a regular expression. Here's one from the MS forums using C#:

Url validation with Regular Expression

But you should really validate this before it gets sent to the server. If you use the Peter Blum validators, he's already done the work for you.

Peter Blum's Validators

Or if you want to put in your own JavaScript file, check out this StackOverflow thread.

Url Validation using jQuery

Community
  • 1
  • 1
PeterB
  • 1,864
  • 1
  • 12
  • 9
  • Though in this case it's not terribly important, if you were validating many URLs, Uri.IsWelFormedUriString is about 100 times faster than uncompiled RegEx and about 10 times faster than compiled RegEx (actual performance, of course, depends on the specific regex expression). But it has the further advantage of being a single line of code. – Pete Dec 17 '12 at 14:28
  • Agreed, Pete. I could write horror stories about how RegEx has been misapplied in a critical path and killed performance. Use only as a last resort. And here the specific problem here is that he needs to make sure it is a website address. I'd use a jQuery function at the client to solve the problem. - Cheers – PeterB Dec 17 '12 at 14:35