URL Validator
-
:confused:Does anyone have a textbox based control that will only accept valid URLs? camasmartin hobby programmer
-
:confused:Does anyone have a textbox based control that will only accept valid URLs? camasmartin hobby programmer
Handle the
Validating
even on aTextBox
(or overrideOnValidating
if deriving fromTextBox
) and in your validation code, use aRegex
instance to check the URL, settingCancelEventArgs.Cancel
totrue
if the regular expression fails. The regular expression you use is determined by what "URL"s you want to support. The concept of URLs - which is a form of URI - is very vague. Any protocol scheme is allows, though they might not match any protocol handlers. Common schemes are http(s), ftp(s), nntp, news, mailto, gopher, and telnet. Windows adds some (depending on what's installed) like ms-help, its, and some others. You can add them to Mozilla/Netscape, too. And each of these can have slightly different syntax that others don't support. My advice - unless you want several regular expressions that will slow validation tremendously, just use theUri
class like so:public class UrlBox : TextBox
{
// ...
protected override void OnValidating(CancelEventArgs e)
{
try
{
new Uri(this.Text);
}
catch
{
e.Cancel = true;
}
}
}This should handle most variants of URLs.
Microsoft MVP, Visual C# My Articles
-
Handle the
Validating
even on aTextBox
(or overrideOnValidating
if deriving fromTextBox
) and in your validation code, use aRegex
instance to check the URL, settingCancelEventArgs.Cancel
totrue
if the regular expression fails. The regular expression you use is determined by what "URL"s you want to support. The concept of URLs - which is a form of URI - is very vague. Any protocol scheme is allows, though they might not match any protocol handlers. Common schemes are http(s), ftp(s), nntp, news, mailto, gopher, and telnet. Windows adds some (depending on what's installed) like ms-help, its, and some others. You can add them to Mozilla/Netscape, too. And each of these can have slightly different syntax that others don't support. My advice - unless you want several regular expressions that will slow validation tremendously, just use theUri
class like so:public class UrlBox : TextBox
{
// ...
protected override void OnValidating(CancelEventArgs e)
{
try
{
new Uri(this.Text);
}
catch
{
e.Cancel = true;
}
}
}This should handle most variants of URLs.
Microsoft MVP, Visual C# My Articles
Thank you.:) With some tuning, it will come close enough. I didn't know about the Uri class. camasmartin hobby programmer Learning every day