I'm making an ecommerce application and I want the user to be able to put content at a URL they have specified. IF a user were to put in something like "/thank-you!", how can I clean the string to either be a valid URL or check this is valid URL format? I would want the url to basically always be hyphened between words so like "/thank-you" from "/thankyou". What's the best approach for achieving such a thing. I'm within c# using .NET MVC 4.
Asked
Active
Viewed 717 times
1 Answers
3
Alas, I cannot comment 'possible duplicate' yet (How to check whether a string is a valid HTTP URL?). As this must be an answer however, one way to validate a string URL would be using the URI.TryCreate functioanlity. See here also https://msdn.microsoft.com/en-us/library/system.uri.trycreate(v=vs.110).aspx
URI is also the preferred data type for URLs, rather than strings.

Community
- 1
- 1
-
1You might not be able to comment but you can still [flag it as a possibe duplicate](http://stackoverflow.com/help/privileges/flag-posts), which is what's really happening when users "write" such comments. – Visual Vincent Sep 18 '16 at 15:56
-
@VisualVincent - Thanks for pointing that out - will do some extra reading. – Sep 18 '16 at 15:58
-
Whoops, my bad. I totally missed this: `* these options will not appear in the flag menu until you have earned 50 reputation (the amount required for commenting).` – Visual Vincent Sep 18 '16 at 15:59
-
Answer accepted by OP. Now you can cast duplicate flags and comment. :) – Visual Vincent Sep 18 '16 at 16:01
-
@VisualVincent You've anticipated my follow up question! I may have incorrectly flagged this as needing moderation in that case. But at least I'll know how to sort it in the future. Thanks again. – Sep 18 '16 at 16:01
-
No problem. You may retract your flag by opening the flag dialog again and pressing `Retract flag`. – Visual Vincent Sep 18 '16 at 16:03
-
After further testing, this didn't solve my problem. If I pass the string to the tryCreate method, it doesn't actually resolve to anything. I wanted to format something like "test something" to "/test-something" – ddeamaral Sep 18 '16 at 20:53
-
In that case, you'd be looking at some string manipulation and regex matching. I would recommend that you try using the string replace function, to switch out the whitespace between words with your hyphen, and add the forward slash at the start if there isn't one. You may need further validation with regards to how many hyphens you add in a row, and whether or not you want one added at the start, end, etc. A word such as 'thankyou' would be much harder to do, unless you hard-code to look for that specific case and add your hyphen. – Sep 18 '16 at 21:38