This blog is moved to
http://amalhashim.wordpress.com

Thursday, June 4, 2009

Validating URL using C#

Regex RgxUrl = new Regex("(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)?/{0,2}[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?");
if (RgxUrl.IsMatch(txtUrl.Text))
{
MessageBox.Show("URL is valid.");
}
else
{
MessageBox.Show("URL is invalid!");
}

The above code will validate URL's without http also. Alternatively you can use this

System.Globalization.CompareInfo cmpUrl = System.Globalization.CultureInfo.InvariantCulture.CompareInfo;
if(cmpUrl.IsPrefix(txtUrl.Text, "http://") == false)
{
txtUrl.Text = "http://" + txtUrl.Text;
}
Regex RgxUrl = new Regex("(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)?/{0,2}[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?");
if (RgxUrl.IsMatch(txtUrl.Text))
{
MessageBox.Show("URL is valid.");
}
else
{
MessageBox.Show("URL is invalid!");
}

1 comment:

lauren said...

Thanks for posting the code to validate url using c#.But I am not good at regular expressions. can you give some brief explaination on them.It will help me to understand these better.Thanks
digital certificates